Go parser not detecting Doc comments on struct type

前端 未结 2 478
借酒劲吻你
借酒劲吻你 2020-12-30 06:11

I am trying to read the assocated Doc comments on a struct type using Go’s parser and ast packages. In this example, the code simply uses itself as the source.



        
2条回答
  •  礼貌的吻别
    2020-12-30 06:31

    You need to use the go/doc package to extract documentation from the ast:

    package main
    
    import (
        "fmt"
        "go/doc"
        "go/parser"
        "go/token"
    )
    
    // FirstType docs
    type FirstType struct {
        // FirstMember docs
        FirstMember string
    }
    
    // SecondType docs
    type SecondType struct {
        // SecondMember docs
        SecondMember string
    }
    
    // Main docs
    func main() {
        fset := token.NewFileSet() // positions are relative to fset
    
        d, err := parser.ParseDir(fset, "./", nil, parser.ParseComments)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        for k, f := range d {
            fmt.Println("package", k)
            p := doc.New(f, "./", 0)
    
            for _, t := range p.Types {
                fmt.Println("  type", t.Name)
                fmt.Println("    docs:", t.Doc)
            }
        }
    }
    

提交回复
热议问题