简体   繁体   中英

How to get access to a custom type in a reflect.Call return?

I know its not idiomatic to write generic functions in Go, but I want to explore my options before I dive into the go generate .

The problem I have is that the Value.Call() returns a slice where the element I interested in is a pointer to a custom struct. Seems like I cant find a way to access this.

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
fmt.Println(returns)

output

[<vspk.EnterpriseProfilesList Value> <*bambou.Error Value>]

type definition:

type EnterpriseProfilesList []*EnterpriseProfile

I want to get access to the vspk.EnterpriseProfilesList , but I am struggling to make it.

If I try to retrieve the underlying value like this:

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
ret1 := returns[0].Interface()
fmt.Println(ret1)

I receive

[0xc0000fc7e0]

Value.Call() returns a value of type []reflect.Value . What you're interested in is the first value of that slice: returns[0] .

This will be of course of type reflect.Value . To extract the value wrapped in it, use Value.Interface() .

This will be of type interface{} . If you need the concrete type, use a type assertion :

returns[0].Interface().(spk.EnterpriseProfilesList)

For example:

if list, ok := returns[0].Interface().(spk.EnterpriseProfilesList); ok {
    // here list is of type spk.EnterpriseProfilesList
} else {
    // it was nil or not of type spk.EnterpriseProfilesList
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM