简体   繁体   中英

casting reflected value to type in golang?

Is it possible to dynamically cast a value generated by reflect.Zero/New back to an arbitrary type?

https://blog.golang.org/laws-of-reflection seems to suggest not (as go is statically typed). That pretty much seems to limit the uses of reflection as far as I can see, as you always need to be aware of the type you are working with.

Here's an example of what I mean:

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    Name string
}

func main() {

    a := &A{Name: "Dave"}
    fmt.Println(a)

    //create a nil pointer of an arbitrary type
    dynamicType := reflect.TypeOf(a)
    dynamicNil := reflect.Zero(dynamicType).Interface()
    a = dynamicNil //is it possible to do this without explicitly casting to A (ie. avoiding `a = dynamicNil.(*A)`)
    fmt.Println(a)
}

Your question's prose and code contradict.

In your code, dynamicNil has the type interface{} , not reflect.Value as the prose suggests. As a has concrete type *A you'll have to type-assert dynamicNil to *A . There's no way around that.

Also note that Go doesn't have casts -- only type-conversions and assertions.

Edit: maybe you're looking for reflect.Value.Set ? it's unclear to me.

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