Creating Objects Using Typed Generics in Go 1.18
In Go 1.18, generics allow the creation of functions that work with any data type. However, creating a new object of a specific type within a generic function requires specific syntax.
Implementing the Create Function
For example, consider a function "Create" that should create a new instance of the struct "Apple." To achieve this in generics:
type FruitFactory[T any] struct{} func (f FruitFactory[T]) Create() *T { // How to create non-nil fruit here? return nil // Placeholder, don't return nil } type Apple struct { color string }
Approach 1: Using a Type Variable
If "Apple" is not a pointer type, a typed variable can be declared and its address returned:
func (f FruitFactory[T]) Create() *T { var a T // Declare variable of type T return &a // Return address of variable }
Approach 2: Using the "new" Function
Alternatively, the "new" function can be used to create a new object:
func (f FruitFactory[T]) Create() *T { return new(T) }
Handling Pointer Types
In case "FruitFactory" is instantiated with a pointer type, a more involved approach is necessary:
// Constraining type to its pointer type type Ptr[T any] interface { *T } // Type parameters: FruitFactory (pointer type), FruitFactory (non-pointer type) type FruitFactory[T Ptr[U], U any] struct{} func (f FruitFactory[T,U]) Create() T { var a U // Declare non-pointer type variable return T(&a) // Convert to pointer type } type Apple struct { color string }
By following these approaches, it is possible to create new objects of any type using generics in Go 1.18.
The above is the detailed content of How Can I Create Objects of a Specific Type within a Generic Function in Go 1.18?. For more information, please follow other related articles on the PHP Chinese website!