英文:
Go command to get list of keywords or reserved words?
问题
在Python中,可以使用keyword
模块提供的命令来列出关键字。示例代码如下:
import keyword
print(keyword.kwlist)
这将输出Python中的关键字列表:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
在Go语言中是否有类似的方法呢?
英文:
In python they have provided command to list the keywords in it by
>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
is there a similar way in go?
答案1
得分: 2
token
包中有一个名为IsKeyword
的函数。该代码检查字符串在以下变量中的存在:
var keywords map[string]Token
不幸的是,这个变量没有被导出。但你可以像标准库中那样构建相同的映射:
func init() {
keywords = make(map[string]Token)
for i := keyword_beg + 1; i < keyword_end; i++ {
keywords[tokens[i]] = i
}
}
keyword_beg
和keyword_end
是常量值,标记关键字常量的开始和结束。它们也没有被导出,但你仍然可以使用这些值(分别解析为60和86)。
因此,你可以将从60到86的整数值转换为token.Token
,然后调用Token.String
。就像这样:
tokens := make([]token.Token, 0)
for i := 61; i < 86; i++ {
tokens = append(tokens, token.Token(i))
}
fmt.Println(tokens)
英文:
The token
package has a function IsKeyword
. The code checks the existence of the string in
var keywords map[string]Token
This var is not exported, unfortunately. But you can build the same map like it is done in the standard lib:
func init() {
keywords = make(map[string]Token)
for i := keyword_beg + 1; i < keyword_end; i++ {
keywords[tokens[i]] = i
}
}
keyword_beg
and keyword_end
are constant values that mark beginning and end of the keyword constants. These also are not exported, but you can still use the value (resolved to 60 and 86).
So you convert int values from 60 to 86 to token.Token
and then call Token.String
. Like this
tokens := make([]token.Token, 0)
for i := 61; i < 86; i++ {
tokens = append(tokens, token.Token(i))
}
fmt.Println(tokens)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论