【问题标题】:Type assertion syntax using go/ast使用 go/ast 类型断言语法
【发布时间】:2019-01-12 13:50:40
【问题描述】:

我已经阅读了下面这段代码,但我不知道它的语法到底是什么 d.()if f, ok := d.(*ast.FuncDecl); 意思是。

谁能帮我解释一下?

package main

import (
    "go/ast"
    "go/parser"
    "go/token"
    "regexp"

    "github.com/posener/complete"
)

func functionsInFile(path string, regexp *regexp.Regexp) (tests []string) {
    fset := token.NewFileSet()
    f, err := parser.ParseFile(fset, path, nil, 0)
    if err != nil {
        complete.Log("Failed parsing %s: %s", path, err)
        return nil
    }
    for _, d := range f.Decls {
        if f, ok := d.(*ast.FuncDecl); ok {
            name := f.Name.String()
            if regexp == nil || regexp.MatchString(name) {
                tests = append(tests, name)
            }
        }
    }
    return
}

【问题讨论】:

标签: go


【解决方案1】:

正如 cmets 所说,这是一个类型断言。 Go 规范中描述了类型断言:https://golang.org/ref/spec#Type_assertions

应用于您的特定代码示例,我认为它取自 AST module documentation,如果您想使用 Go AST,您应该阅读它。

ParseFile 返回一个ast.File,即:

type File struct {
        Doc        *CommentGroup   // associated documentation; or nil
        Package    token.Pos       // position of "package" keyword
        Name       *Ident          // package name
        Decls      []Decl          // top-level declarations; or nil
        Scope      *Scope          // package scope (this file only)
        Imports    []*ImportSpec   // imports in this file
        Unresolved []*Ident        // unresolved identifiers in this file
        Comments   []*CommentGroup // list of all comments in the source file
}

所以DeclsDecl 的一部分,这是一个接口。简而言之,这意味着在编译时你不知道实际的底层类型是什么(尽管你知道它满足接口),所以你做一个运行时类型断言来验证它是你所期望的。

    if f, ok := d.(*ast.FuncDecl); ok {
        name := f.Name.String()
        if regexp == nil || regexp.MatchString(name) {
            tests = append(tests, name)
        }
    }

这意味着“如果d 实际上是FuncDecl,就做这件事”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多