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


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)

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):
enter image description here

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)


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


Then you can access blk.List.

Answered By – Burak Serdar

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.