In Go, the "fmt" package provides a variety of functions for formatted output. When you want to escape special characters in the output, you can use the %q
verb with the fmt.Printf
or fmt.Sprintf
functions.
Here's an example that demonstrates escaping special characters using fmt.Printf
:
package main
import "fmt"
func main() {
name := "John Doe"
fmt.Printf("Hello, %q!\n", name)
}
In the code above, the %q
verb is used to escape special characters in the name
variable. It will enclose the string value in double quotes and properly escape any special characters present within the string.
The output of the above code will be:
Hello, "John Doe"!
Similarly, you can use the %q
verb in fmt.Sprintf
to escape special characters and get a formatted string without printing it to the standard output.
package main
import "fmt"
func main() {
name := "John Doe"
formattedString := fmt.Sprintf("Hello, %q!", name)
fmt.Println(formattedString)
}
The output will be the same as before:
Hello, "John Doe"!
By using %q
, you can ensure that special characters are properly escaped in the formatted output.