Home >Backend Development >Golang >How Can I Implement Multiple Interfaces in Go for a Single Type?
Go does not support multiple inheritance, but it is possible to implement multiple interfaces for a single type. This allows you to define a type that conforms to the requirements of multiple interfaces.
In your example, you have a Card interface and a card struct that implements the Card interface. You want to be able to use the Card interface to represent cards, but you also want to have a string representation of the cards.
To solve this, you could define a Stringer interface:
type Stringer interface { String() string }
And then have the card struct implement both the Card and Stringer interfaces:
type card struct { cardNum int face string suit string } func (c *card) GetFace() string { return c.face } func (c *card) GetSuit() string { return c.suit } func (c *card) String() string { return fmt.Sprintf("%s%s", c.GetFace(), c.GetSuit()) }
This would allow you to use the Card interface to represent cards, and you could also use the Stringer interface to get a string representation of the cards.
Note that this approach does not hide the implementation details of the card struct. If you want to truly hide the implementation details, you could use a factory function to create Card values, and then only return the Card interface to clients.
func NewCard(num int) Card { newCard := card{ cardNum: num, face: faces[num%len(faces)], suit: suits[num/len(faces)], } return &newCard }
This would allow you to create Card values without exposing the implementation details of the card struct.
The above is the detailed content of How Can I Implement Multiple Interfaces in Go for a Single Type?. For more information, please follow other related articles on the PHP Chinese website!