【发布时间】:2017-05-02 04:49:29
【问题描述】:
我不想深入探讨以下情况的基本原理。它与解组可以是任何一组固定类型的序列化对象有关,但您不知道是哪种类型。
我有以下类型:
type I interface {
Do()
}
type someI struct {}
func (i *someI) Do() {}
type otherI struct {}
func (i *otherI) Do() {}
因此,两个结构其中的指针实现了接口I。
现在我有这个方法想要返回一个I 类型的值:
func GetSomeI(marshalled []byte) (I, error) {
var obj interface{}
// The following method magically puts an instance
// of either someI or otherI into obj.
magicUnmarshall(marshalled, obj)
// The problem now is that we cannot return obj,
// because the raw structs don't implement I.
// One solution would be to do a type switch like this:
switch obj.(type) {
case someI:
i := obj.(someI)
return &i, nil
case otherI:
i := obj.(otherI)
return &i, nil
default:
return nil, errors.New("marschalled object was not of type I")
}
// But now consider the case that there are quite some
// different implementations of I.
// We would prefer to have a general way of getting
// a reference to obj.
}
【问题讨论】:
标签: pointers go types interface