Search code examples
goabstract-syntax-tree

What is the difference between Doc and Comment in go/ast package?


I am using the go/ast and go/parser package to do something, but i am puzzled about the difference between Doc and Comment.

Is the first line of comments a Doc, then others as Comment?
Here is a sample:

TypeSpec struct {
    Doc     *CommentGroup // associated documentation; or nil
    Name    *Ident        // type name
    Type    Expr          // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
    Comment *CommentGroup // line comments; or nil
}

Solution

  • From src/go/ast/ast.go#L70-L75:

    // A CommentGroup represents a sequence of comments
    // with no other tokens and no empty lines between.
    

    Following Godoc: documenting Go code:

    • Doc is one or several continuous lines of comments (// ...) before the TypeSpec

    write a regular comment directly preceding its declaration, with no intervening blank line

    // A TypeSpec node represents a type declaration (TypeSpec production).
    ^^^^^^^^^^^^...
    TypeSpec struct {
    
    • Comment is a comment associate to the field itself, starting on the same line, but which can spread over multiple continuous lines (hence "CommentGroup")

      Name    *Ident        // type name
                            ^^^^^^^^^^^
                            // the comment associated to Name
                            // could go on over several lines