简体   繁体   中英

convert struct pointer to interface{}

If I have:

   type foo struct{
   }

   func bar(baz interface{}) {
   }

The above are set in stone - I can't change foo or bar. Additionally, baz must converted back to a foo struct pointer inside bar. How do I cast &foo{} to interface{} so I can use it as a parameter when calling bar?

To turn *foo into an interface{} is trivial:

f := &foo{}
bar(f) // every type implements interface{}. Nothing special required

In order to get back to a *foo , you can either do a type assertion :

func bar(baz interface{}) {
    f, ok := baz.(*foo)
    if !ok {
        // baz was not of type *foo. The assertion failed
    }

    // f is of type *foo
}

Or a type switch (similar, but useful if baz can be multiple types):

func bar(baz interface{}) {
    switch f := baz.(type) {
    case *foo: // f is of type *foo
    default: // f is some other type
    }
}

使用反映

reflect.ValueOf(myStruct).Interface().(newType)

Not fully-related, but I googled the question "convert interface struct to pointer" and get here.

So, just make a note: to convert an interface of T to interface of *T :

//
// Return a pointer to the supplied struct via interface{}
//
func to_struct_ptr(obj interface{}) interface{} {
    vp := reflect.New(reflect.TypeOf(obj))
    vp.Elem().Set(reflect.ValueOf(obj))
    return vp.Interface()
}

Converting a struct to interface can be achieved like this. Where i is an assign data structure.

var j interface{} = &i

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