Home > Software design >  Go command to get list of keywords or reserved words?
Go command to get list of keywords or reserved words?

Time:10-17

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?

CodePudding user response:

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)
  •  Tags:  
  • go
  • Related