goabstract-syntax-tree

Why Golang ast.Field can have multiple names?


Just playing around with golang go/ast package.

I don’t quite understand why ast.Field can have multiple names?

type Field struct {
    Doc     *CommentGroup // associated documentation; or nil
    Names   []*Ident      // field/method/(type) parameter names; or nil
    Type    Expr          // field/method/parameter type; or nil
    Tag     *BasicLit     // field tag; or nil
    Comment *CommentGroup // line comments; or nil
}

Upd. Thanks to the @kurtis-rader

I want to create cli tool that will generate struct conversion functions from one struct type to another. Here in this place I need to choose which name of Field to pass into struct literal as a key and value


Solution

  • ast.Field represents a field declaration (and other things with a similar syntax). A field declaration can have more than one identifier.

    Here is the syntax from the specification:

    StructType    = "struct" "{" {     FieldDecl ";" } "}" .
    FieldDecl     = (IdentifierList Type |     EmbeddedField) [ Tag ] .
    EmbeddedField = [ "*" ] TypeName [ TypeArgs ] .
    Tag          = string_lit .  
    

    Example:

    struct {
        A, B int 
    }