convert struct pointer to interface{}

前端 未结 3 1885
孤街浪徒
孤街浪徒 2021-01-30 03:16

If I have:

   type foo struct{
   }

   func bar(baz interface{}) {
   }

The above are set in stone - I can\'t change foo or bar. Additionally,

3条回答
  •  [愿得一人]
    2021-01-30 03:59

    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()
    }
    

提交回复
热议问题