问题描述
我在Go中的语法树中走来走去,试图找到对某个特定函数的所有调用,然后获取其字符串参数(这是文件名,应为字符串文字,而不是其他任何标识符).我已经成功完成了,现在我有了ast.BasicLit
节点和Kind == token.STRING
,但是它的值是Go代码,而不是它应该具有的字符串值.
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
但是我想要相反的东西-类似于eval函数(但仅适用于Go字符串文字).
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).
您应该注意的一件事是,strconv.Unquote()
只能取消对引号中的字符串的引用(例如,以引号char "
或反引号char `
开头和结尾),因此您必须手动如果没有引号,请附加.
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.
示例:
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\nSecondline"`))
输出(在游乐场上尝试):
invalid syntax
invalid syntax
Hi <nil>
Hi! <nil>
First line
Secondline <nil>
这篇关于如何将Go字符串文字代码转换为其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!