I want an interface that can pass arguments of any type to its individual methods, and I want an interface with A single implementation structure for generics.
This is a super simplified version of my problem:
package main type MyInterface interface { Set(val any) } type MyStruct[T any] struct { val T } func NewMyStruct[T any]() *MyStruct[T] { return &MyStruct[T]{} } func (s *MyStruct[T]) Set(val T) { s.val = val } func main() { var obj MyInterface obj = NewMyStruct[any]() // accepted obj = NewMyStruct[int]() // not accepted obj = NewMyStruct[string]() // not accepted }
Is there a way to satisfy the compiler's requirements without losing the type information of the Set method when directly processing the structure?
I think your code can be modified like this
package main import "fmt" type MyInterface[T any] interface { Set(value T) } type MyStruct[T any] struct { val T } func NewMyStruct[T any]() *MyStruct[T] { return &MyStruct[T]{} } func (s *MyStruct[T]) Set(val T) { s.val = val } func main() { var obj1 MyInterface[int] obj1 = NewMyStruct[int]() var obj2 MyInterface[string] obj2 = NewMyStruct[string]() var obj3 MyInterface[any] obj3 = NewMyStruct[any]() }
Whenever a parameterized type is used, the type parameters in its definition must be replaced with the actual type. This means that the generic type in the interface must be instantiated. For this, your interface should be declared like this.
// As-is type MyInterface interface { Set(val any) } // To-be type MyInterface[T any] interface { Set(val T) }
And when using it, you should be clear about what type the any
is using.
func main() { var obj1 MyInterface[int] obj1 = NewMyStruct[int]() }
I quoted two pages
[1] Go error: Cannot use a generic non-instantiated type
[2] How to implement a universal interface?
The above is the detailed content of Implementing interface methods using generic type structures in Go. For more information, please follow other related articles on the PHP Chinese website!