convert struct pointer to interface{}

前端 未结 3 1887
孤街浪徒
孤街浪徒 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 04:02

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

提交回复
热议问题