Go:尽管在文档中存在,但接口的属性未定义。

huangapple go评论72阅读模式
英文:

Go: Property of an interface is undefined despite existing in the documentation

问题

我正在编写一个遍历抽象语法树(AST)的程序。当我执行以下代码片段时:

val := reflect.Indirect(reflect.ValueOf(currStatement))
for i := 0; i < val.NumField(); i++ {
    varName := val.Type().Field(i).Name
    varType := val.Type().Field(i).Type
    varValue := val.Field(i).Interface()

    if (varName == "Body") {
        fmt.Printf("%v %v %v\n", varName,varType,varValue)
    }
}
fmt.Println()

我得到以下输出:

Body *ast.BlockStmt &{2795 [0xc0001044c0] 2867}

这表明val.Field(i).Interface()的类型是*ast.BlockStmt。然而,根据这里的文档(https://pkg.go.dev/go/ast#BlockStmt):

Go:尽管在文档中存在,但接口的属性未定义。

可以明确看到BlockStmt具有属性List。然而,当我在for循环中运行以下代码行以提取属性List的值(最终我将遍历它):

fmt.Printf("%v %v %v\n", varName,varType,varValue.List)

我得到以下错误:

varValue.List undefined (type interface {} is interface with no methods)
英文:

I am writing a program that iterates through an AST (abstract syntax tree). When I execute the following piece of code:

val := reflect.Indirect(reflect.ValueOf(currStatement))
for i := 0; i &lt; val.NumField(); i++ {
	varName := val.Type().Field(i).Name
	varType := val.Type().Field(i).Type
	varValue := val.Field(i).Interface()

	if (varName == &quot;Body&quot;) {
		fmt.Printf(&quot;%v %v %v\n&quot;, varName,varType,varValue)
	}
}
fmt.Println()

I get the following output:

Body *ast.BlockStmt &amp;{2795 [0xc0001044c0] 2867}   

Which indicates that val.Field(i).Interface() is the type *ast.BlockStmt. However, according to the documentation here (https://pkg.go.dev/go/ast#BlockStmt):
Go:尽管在文档中存在,但接口的属性未定义。

It is clear that BlockStmt has the property List. However, when I run the following line of code in the for loop to extract the value of the property List (which I will eventually iterate through):

fmt.Printf(&quot;%v %v %v\n&quot;, varName,varType,varValue.List)

I get the following error:

varValue.List undefined (type interface {} is interface with no methods)

答案1

得分: 1

varValue 是类型为 interface{} 的变量,指向一个 BlockStmt 实例。你需要使用类型断言来从中获取 BlockStmt

blk := varValue.(*ast.BlockStmt)

然后你可以访问 blk.List

英文:

varValue is of type interface{} that points to a BlockStmt instance. You have to use type-assertion to get the BlockStmt from it:

blk:=varValue.(*ast.BlockStmt)

Then you can access blk.List.

huangapple
  • 本文由 发表于 2022年1月26日 07:48:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/70857139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定