在Go 中,一個泛型不能被賦值給另一個,即使它們的類型參數可能是由於泛型實例化的性質所致。
通用類型Go
泛型類型允許透過定義可與不同資料類型一起使用的範本來重複使用程式碼。實例化泛型類型時,您可以提供特定類型參數來指定所使用的特定資料類型。
賦值限制
將一種泛型類型的值分配給另一種泛型類型可能會並不總是被允許。這是因為使用不同類型參數實例化泛型類型會產生兩個不同的命名類型。
例如:
type Props[G Generic] struct{} type Example struct{} func (Example) ID() string { return "" } var ExampleProps = Props[Example]{} func Problem() Props[Generic] { return ExampleProps // Compilation error }
在此範例中,Example 實作了 Generic 介面。但是,Props[Example] 和 Props[Generic] 仍然被視為不同的類型。因此,不允許將ExampleProps(類型為Props[Example])指派給Problem(返回Props[Generic])。
解
如果你想要在泛型型別之間指派值,可以使用型別參數來實例化泛型型別。例如:
func Problem[T Generic](v T) Props[T] { return Props[T]{Value: v} }
在這種情況下,Problem 會採用泛型參數 T 並以 T 實例化 Props。這提供了更大的靈活性,可以在類型參數滿足特定條件的情況下使用。
以上是為什麼我不能在 Go 中將一種泛型類型指派給另一種類型,即使它們的類型參數相容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!