How to use the strconv.Quote() function in Go

The strconv.Quote() function

The strconv package’s Quote() function is used to get a double-quoted Go string literal representing the specified string s. For control characters and non-printable characters, the resulting string employs Go escape sequences (\t, \n, \xFF, \u0100) as defined by the IsPrint() function.

Syntax

func Quote(s string) string

Parameter

  • s: This is the string value to be returned with the double-quoted string with escape sequences.

Return type

The return type of strconv.Quote() is string.

Return value

The Quote() function returns a double-quoted Go string literal representing the given string.

Example

The following code shows how to use the strconv.Quote() function in Go.

Note: To use the Quote() function, we must first import the strconv package into our program.

// Golang program
// Using strconv.Quote() Function
package main
import (
"fmt"
"strconv"
)
func main() {
// declare a variable of string type
var str string
// assign value
str = `"Keep Coding ☺"`
// Quote() function returns a double-quoted Go
// string literal representing the str value
fmt.Println(strconv.Quote(str))
// reassign value
str = `"Golang is statically typed "`
// Quote() function returns a double-quoted Go
//string literal representing the str value
fmt.Println(strconv.Quote(str))
}

Code explanation

  • Line 4: We add the package main.

  • Line 6 to 9: We import necessary packages in the Golang project.

  • Line 11 to 21: We define the main() function, variable str of string type and assign a value to it, and pass the variable in the Quote() function which returns a single-quoted Go character literal representing the given string value. Finally, the result is displayed.

Free Resources