具有不同結果類型的函數類型是不同的類型,如果其中一個結果類型實現另一個類型,則無關緊要。 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!")
}