我在 go 1.18 的 beta 版本中使用泛型。下面示例中的創建函式應該創建*T(因此*Apple)的新實體。我嘗試為此使用反射包,但沒有運氣。
你能告訴我如何Create從下面的示例中更改函式,以便它創建實體T而不是回傳 nil 并使我的示例崩潰嗎?
type FruitFactory[T any] struct{}
func (f FruitFactory[T]) Create() *T {
//how to create non-nil fruit here?
return nil
}
type Apple struct {
color string
}
func example() {
appleFactory := FruitFactory[Apple]{}
apple := appleFactory.Create()
//panics because nil pointer access
apple.color = "red"
}
uj5u.com熱心網友回復:
由于您正在FruitFactory使用非指標型別 ( Apple)進行實體化,因此您只需宣告一個型別變數并回傳其地址:
func (f FruitFactory[T]) Create() *T {
var a T
return &a
}
或者:
func (f FruitFactory[T]) Create() *T {
return new(T)
}
游樂場:https : //gotipplay.golang.org/p/IJErmO1mrJh
如果您想FruitFactory使用指標型別實體化并仍然避免分段錯誤,事情會變得更加復雜。基本上,您必須利用型別推斷在方法體中宣告一個非指標型別的變數并將其轉換為指標型別。
// constraining a type to its pointer type
type Ptr[T any] interface {
*T
}
// the first type param will match pointer types and infer U
type FruitFactory[T Ptr[U], U any] struct{}
func (f FruitFactory[T,U]) Create() T {
// declare var of non-pointer type. this is not nil!
var a U
// address it and convert to pointer type (still not nil)
return T(&a)
}
type Apple struct {
color string
}
func main() {
// instantiating with ptr type
// second type param U is inferred from the first
appleFactory := FruitFactory[*Apple]{}
apple := appleFactory.Create()
// all good
apple.color = "red"
fmt.Println(apple) // &{red}
}
游樂場:https : //gotipplay.golang.org/p/07nUGI-xP0O
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/384261.html
