When printing a string in Go you can use the verb %q
in the format parameters of fmt
functions, when available, to safely escape a string and add quotes to it.
For example:
import "fmt"
func main() {
fmt.Printf("%s\n", "hello") // prints hello
fmt.Printf("%q\n", "hello") // prints "hello"
fmt.Printf("%s\n", "hello\n;") // prints hello
//; \n is not escaped
fmt.Printf("%q\n", "hello\n;") // prints "hello\n;" \n is escaped here
}
For a more in-depth overview head to the fmt
package reference.
Top comments (0)