How to Use strconv.CanBackquote() Function in Golang

Golang strconv.CanBackquote() function is used to check whether the string can be represented unchanged as a single-line backquoted string without control characters other than a tab”.

Syntax

func CanBackquote(str string) bool

Parameters

str: It takes one parameter of string type, i.e., str.

Return value

The CanBackquote() function returns true if the str can be represented unchanged as a single-line backquoted string. Otherwise, it returns false.

Example 1: How to Use strconv.CanBackquote() Function

package main

import (
  "fmt"
  "strconv"
)

func main() {
  fmt.Println(strconv.CanBackquote("We are the world"))
  fmt.Println(strconv.CanBackquote("`We are the world`"))
  fmt.Println(strconv.CanBackquote(`"We are the world"`))
}

Output

true
false
true

Example 2: Complex code of strconv.CanBackquote() function

package main

import (
  "fmt"
  "strconv"
  "strings"
)

func main() {
  stringList := []string{"Hello, world!", "New\nLine", "Tab\tCharacter", 
                         "Contains ` backquote", `Contains " quote`, "Plain text"}

  for _, str := range stringList {
    if strconv.CanBackquote(str) {
      fmt.Printf("Can Backquote: `%s`\n", str)
    } else {
    // If the string can't be backquoted as is, we'll
    // print it in double quotes with standard escaping.
      fmt.Printf("Cannot Backquote: %q\n", str)
    }
  }

  fmt.Println("\nReplace problematic characters and retry:\n")

  // Let's replace newlines, tabs, and backquotes and try again
  for _, str := range stringList {
    str = strings.ReplaceAll(str, "\n", "\\n")
    str = strings.ReplaceAll(str, "\t", "\\t")
    str = strings.ReplaceAll(str, "`", "'")

    if strconv.CanBackquote(str) {
      fmt.Printf("Can Backquote: `%s`\n", str)
    } else {
      // If the string can't be backquoted as is, we'll
      // print it in double quotes with standard escaping.
      fmt.Printf("Cannot Backquote: %q\n", str)
    }
  }
}

Output

Can Backquote: `Hello, world!`
Cannot Backquote: "New\nLine"
Can Backquote: `Tab Character`
Cannot Backquote: "Contains ` backquote"
Can Backquote: `Contains " quote`
Can Backquote: `Plain text`

Replace problematic characters and retry:

Can Backquote: `Hello, world!`
Can Backquote: `New\nLine`
Can Backquote: `Tab\tCharacter`
Can Backquote: `Contains ' backquote`
Can Backquote: `Contains " quote`
Can Backquote: `Plain text`

This code has a slice of different strings that include various special characters.

We check for each string to see if it can be represented as a single-line backquoted string without further escaping using strconv.CanBackquote(). If it can, we print it as a backquoted string. If not, we print it as a standard escaped double-quoted string.

That’s it.

Leave a Comment