获取关键字或保留字列表的Go命令是什么?

huangapple go评论91阅读模式
英文:

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_begkeyword_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 &lt; 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 &lt; 86; i++ {
	tokens = append(tokens, token.Token(i))
}
fmt.Println(tokens)

huangapple
  • 本文由 发表于 2021年10月15日 22:34:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/69586412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定