Generic Method Parameters in Golang
In Golang, to enable a function to accept any type, generic method parameters can be used. When a method requires a type that has a particular property, interfaces can be employed. Below is an example where a function needs to accept types that possess an ID property.
<code class="go">type MammalImpl struct { ID int Name string } func (m MammalImpl) GetID() int { return m.ID } func (m MammalImpl) GetName() string { return m.Name } type HumanImpl struct { MammalImpl HairColor string } func (h HumanImpl) GetHairColor() string { return h.HairColor }</code>
In this code, interfaces have been defined along with their embedded implementations for Mammal and Human. This ensures that both types can be used in the Count function, which now accesses the ID property indirectly through the GetID method.
<code class="go">func Count(ms []Mammal) *[]string { IDs := make([]string, len(ms)) for i, m := range ms { IDs[i] = strconv.Itoa(m.GetID()) } return &IDs }</code>
By making use of generic method parameters and interfaces, this function can now process both slices of Mammal and Human objects.
Here is the complete working code:
<code class="go">import ( "fmt" "strconv" ) type Mammal interface { GetID() int GetName() string } type Human interface { Mammal GetHairColor() string } type MammalImpl struct { ID int Name string } func (m MammalImpl) GetID() int { return m.ID } func (m MammalImpl) GetName() string { return m.Name } type HumanImpl struct { MammalImpl HairColor string } func (h HumanImpl) GetHairColor() string { return h.HairColor } func Count(ms []Mammal) *[]string { IDs := make([]string, len(ms)) for i, m := range ms { IDs[i] = strconv.Itoa(m.GetID()) } return &IDs } func main() { mammals := []Mammal{ MammalImpl{1, "Carnivorious"}, MammalImpl{2, "Ominivorious"}, } humans := []Mammal{ HumanImpl{MammalImpl: MammalImpl{ID: 1, Name: "Peter"}, HairColor: "Black"}, HumanImpl{MammalImpl: MammalImpl{ID: 2, Name: "Paul"}, HairColor: "Red"}, } numberOfMammalIDs := Count(mammals) numberOfHumanIDs := Count(humans) fmt.Println(numberOfMammalIDs) fmt.Println(numberOfHumanIDs) }</code>
The above is the detailed content of How can I use generic method parameters and interfaces to process both slices of Mammal and Human objects in Golang?. For more information, please follow other related articles on the PHP Chinese website!