Cloud
Cloud

Reputation: 3219

Golang not escape a string variable

We can use "`" to not escape a string:

package main

import "fmt"

func main()  {
    fmt.Println(`abc\tdef`) // abc\tdef
}

But how to get or print a non-escaped string variable?

package main

import "fmt"

func main()  {
    s := "abc\tdef"
    fmt.Println(s) // abc def
}

Upvotes: 0

Views: 7903

Answers (1)

Cloud
Cloud

Reputation: 3219

Use %#v and Sprintf:

package main

import "fmt"

func main()  {
    s := "abc\tdef"
    s = fmt.Sprintf("%#v", s)
    fmt.Println(s) // "abc\tdef"
}

%#v: a Go-syntax representation of the value

Sprintf: Sprintf formats according to a format specifier and returns the resulting string.

Upvotes: 5

Related Questions