I'm walking around syntax tree in Go, trying to find all calls to some particular function and then get its string argument (it's a file name, and should be string literal, not any other identifier). I'm succeeded with this, and now I have ast.BasicLit
node with Kind == token.STRING
, but its value is Go code, not a value of the string that it should have.
I found question that answers how to do reverse transformation - from string to go code it represents: golang: given a string, output an equivalent golang string literal
But I want the opposite - something like eval function (but just for Go string literals).
You can use the strconv.Unquote()
to do the conversion (unquoting).
One thing you should be aware of is that strconv.Unquote()
can only unquote strings that are in quotes (e.g. start and end with a quote char "
or a back quote char `
), so you have to manually append that if it's not in quotes.
Example:
fmt.Println(strconv.Unquote("Hi")) // Error: invalid syntax
fmt.Println(strconv.Unquote(`Hi`)) // Error: invalid syntax
fmt.Println(strconv.Unquote(`"Hi"`)) // Prints "Hi"
fmt.Println(strconv.Unquote(`"Hi\x21"`)) // Prints "Hi!"
// This will print 2 lines:
fmt.Println(strconv.Unquote(`"First line
Secondline"`))
Output (try it on the Go Playground):
invalid syntax
invalid syntax
Hi <nil>
Hi! <nil>
First line
Secondline <nil>