具有不同结果类型的函数类型是不同的类型,如果其中一个结果类型实现另一个类型,则无关紧要。 Spec: Function types:
函数类型表示集合与相同的参数和结果类型所有功能。
StorageBtype1
和StorageBType
是不同类型的,所以它们具有的功能类型作为其结果类型也不同,并且这些函数类型中的一个的值不能被用作用于其它的值。
简单地改变结果类型的所有转换器功能StorageBType
:
func TypeA3ToTypeB1(i StorageAType) StorageBType {
return StorageBType1{i.Type}
}
func TypeA5ToTypeB2(i StorageAType) StorageBType {
return StorageBType2{i.Type, i.Name}
}
由于所有的返回值实现StorageBType
,这是一个有效的变化和需要的转换器功能的实现没有变化。
当然,现在调用这些函数将返回类型StorageBType
的值。如果这对你来说足够/足够,你就没有什么可做的了。
万一你需要返回的值存储在接口值的具体类型,你可以使用type assertion。
例如:
a := StorageAType{Type:3}
b := TypeA3ToTypeB1(a) // b is of type StorageBType
if b1, ok := b.(StorageBType1); ok {
// b1 is of type StorageBType1, you may use it like so:
fmt.Println("b1.Type:", b1.Type)
} else {
// b is not of type StorageBType1, or it is nil
}
输出:
b1.Type: 3
如果你想测试很多具体的类型,你可以使用一个type switch:
switch i := b.(type) {
case nil:
fmt.Println("nil")
case StorageBType1:
// Here i is of type StorageBType1, you may refer to its fields:
fmt.Println("StorageBType1", i.Type)
case StorageBType2:
// Here i is of type StorageBType2, you may refer to its fields:
fmt.Println("StorageBType2", i.Type, i.Name)
default:
fmt.Println("Unhandled type!")
}