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 thestrconvpackage into our program.
// Golang program// Using strconv.Quote() Functionpackage mainimport ("fmt""strconv")func main() {// declare a variable of string typevar str string// assign valuestr = `"Keep Coding ☺"`// Quote() function returns a double-quoted Go// string literal representing the str valuefmt.Println(strconv.Quote(str))// reassign valuestr = `"Golang is statically typed "`// Quote() function returns a double-quoted Go//string literal representing the str valuefmt.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, variablestrof string type and assign a value to it, and pass the variable in theQuote()function which returns a single-quoted Go character literal representing the given string value. Finally, the result is displayed.