package main
import (
"reflect"
"fmt"
)
type Entity interface{
getElement() int32
}
type entityice struct {
elem int32
}
func (ice *entityice) getElement(){
return ice.elem
}
type entityfire struct {
elem int32
}
func (fire *entityfire) getElement(){
return fire.elem
}
var entityTypeRegistry = make(map[byte]reflect.Type)
func main() {
entityTypeRegistry[0] = reflect.TypeOf(entityice{0})
entityTypeRegistry[1] = reflect.TypeOf(entityfire{1})
entity := newEntity(0)
fmt.Println(entity.getElement())
}func newEntity(entType int32) Entity{
reflection := reflect.New(entityTypeRegistry[entType]).Elem().Interface()
switch reflection.(type){
case entityice:
thevar := reflection.(entityice)
thevar.elem = 0
return &thevar
case entityfire:
thevar := reflection.(entityfire)
thevar.elem = 1
return &thevar
}
return nil
}
reflection := reflect.New(entityTypeRegistry[entType]).Elem().Interface()
entity := reflection.(entityTypeRegistry[entType])
return entity
and I cannot type cast interface{} to entityice or entityfire dynamically without getting a build problem :reflection := reflect.New(entityTypeRegistry[entType]).Elem().Interface()
entity := reflection.(entityTypeRegistry[entType])
return entityDo not actually compile:.\main.go:2: entityTypeRegistry[entType] is not a type
On Sep 12, 2015 11:27 AM, <epix...@gmail.com> wrote:
>
> the main problem is the fact that the var "reflection" is actually a "interface{}" type, when I try to cast or return this as an "Entity", I get this error :
>
> .\main.go:46: cannot use reflection (type interface {}) as type Entity in return argument:
> interface {} does not implement Entity (missing getElement method)
>
> and I cannot type cast interface{} to entityice or entityfire dynamically without getting a build problem :
>
> reflection := reflect.New(entityTypeRegistry[entType]).Elem().Interface()
> entity := reflection.(entityTypeRegistry[entType])
> return entity
>
> Do not actually compile:
> .\main.go:2: entityTypeRegistry[entType] is not a type
Define an interface type with the method you want, and convert to that. If there is no common method, then I don't understand what you are trying to do.
Ian
> Le samedi 12 septembre 2015 19:31:05 UTC+2, Ian Lance Taylor a écrit :
>>
>> Here's a tip: fmt.Printf("%T\n", reflection) will print the type of
>> the variable reflection. That may help show you what is going wrong.
>>
>> Ian
>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Yes, but you didn't show us what type the value had. Hence my
suggestion to print it with %T.
You can convert directly to Entity with a type assertion: v.(Entity).