Home >Backend Development >Golang >Can Go Generics Enforce Specific Fields in Passed Values Without Interface Methods?
Ensuring Passed Values Have Specific Fields using Generics in Go
Problem:
Developers often need generic functions in Go that accept values with specific fields. While attempts have been made using various approaches, finding a workable solution has been challenging.
Question:
Can a generic function be implemented in Go to enforce the presence of certain fields (e.g., an "ID int" field) on passed values without employing an interface method (such as "GetID() int")?
Answer:
Regrettably, the answer is no.
In Go's generics implementation for version 1.18, structural types are not supported. Therefore, a method within an interface is necessary to access common fields in passed values.
It's important to clarify that the tilde-type syntax (~T) denotes a set of types whose underlying type is precisely T. So "~struct{ ID int }" does not include structs with an "ID int" field and additional fields.
Although proposals exist to address this limitation, they will not be implemented in Go 1.18.
The above is the detailed content of Can Go Generics Enforce Specific Fields in Passed Values Without Interface Methods?. For more information, please follow other related articles on the PHP Chinese website!