vendredi 18 mai 2018

casting reflected value to type in golang?

Is it possible to dynamically cast a reflect.Value 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)
}





Aucun commentaire:

Enregistrer un commentaire