Home >Backend Development >Golang >How Can I Guarantee Field Presence in Go Generics?
Ensuring Field Presence in Generic Functions
In Go, creating generic functions that accept values with specific fields can be challenging. Using generics, we may attempt to enforce such constraints, as demonstrated in the below example:
package main import ( "fmt" ) func Print[T IDer](s T) { fmt.Print(s.ID) } func main() { Print(Person{3, "Test"}) } type IDer interface { ~struct{ ID int } } type Person struct { ID int Name string } type Store struct { ID int Domain string }
However, this approach fails because Go 1.18's generic implementation lacks structural types support. As a result, we cannot utilize this mechanism to guarantee the presence of specific fields in passed values.
Therefore, in Go, it is necessary to define methods within interfaces to access common fields when dealing with unions or ensuring field presence in generic functions.
The above is the detailed content of How Can I Guarantee Field Presence in Go Generics?. For more information, please follow other related articles on the PHP Chinese website!