英文:
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):
可以明确看到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 < 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()
I get the following output:
Body *ast.BlockStmt &{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):
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("%v %v %v\n", 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论