Home > Article > Backend Development > Use any to instantiate a common interface, struct does not implement it
In this article, editor Youzi will introduce you to the method of using any to instantiate a universal interface, and explain why struct does not implement it. Generic interfaces are a very useful design pattern that allow us to use a more flexible way when writing code. However, when using common interfaces, we need to pay attention to some details to avoid unnecessary problems. Let's take a look at how to properly instantiate a generic interface using any and understand why struct doesn't implement it.
Can someone explain why *DataTo
does not satisfy ToType[any]
?
Try to build a DTOer
that copies all the values from one structure to another and sets some explicit values (V
in this case)
https://go.dev/play/p/-oobZrw5Ewe
// You can edit this code! // Click here and start typing. package main import "fmt" type DataFrom struct { V1 int } type DataTo struct { V int } func (m *DataTo) SetVal() { m.V = 1 return } type ToType[T any] interface { SetVal() *T } type DTO[TFrom any, TTo ToType[any]] struct { Get func(from TFrom) TTo } func main() { dto := &DTO[DataFrom, *DataTo]{ Get: func(from DataFrom) *DataTo { return &DataTo{V: from.V1 + 666} }, } vFrom := DataFrom{V1: 1} vTo := dto.Get(vFrom) fmt.Println(vTo.V) }
Because any
is a static type.
If you use this to instantiate a generic type like ToType
, the generic type will expect exactly any
.
Now, certain uses of type parameters may hide this problem, for example:
type Foo[T any] struct { Value T } Foo[any]{Value: 12} // ok
Normally you can specify any type for any
as above, since any
is just an alias for the empty interface interface{}
, and any type All satisfy the empty interface.
When the type parameter is used for a composite type (e.g. *T
), instantiation using any
means exactly *any
. So you can think of ToType[any]
as the same thing:
type ToTypeAny interface { SetVal() *any }
Then *DataTo
is obviously not *any
. More details: Assigning structure pointer to interface pointer
If you declare the struct as follows, it will compile:
type DTO[TFrom any, TTo ToType[DataTo]] struct { Get func(from TFrom) TTo }
Or in a more "generic" but also more detailed way:
type DTO[TFrom any, T any, TTo ToType[T]] struct { Get func(from TFrom) TTo } &DTO[DataFrom, DataTo, *DataTo]{ ... }
The above is the detailed content of Use any to instantiate a common interface, struct does not implement it. For more information, please follow other related articles on the PHP Chinese website!