I have a Go interface:
type People interface {
GetName() string
GetAge() string
}
Now I want another interface Student
:
1.
type Student interface {
GetName() string
GetAge() string
GetScore() int
GetSchoolName() string
}
But I don't want to write the duplicate function GetName
and GetAge
.
Is there a way to avoid write GetName
and GetAge
in Student
interface ? like:
2.
type Student interface {
People interface
GetScore() int
GetSchoolName() string
}
As we know that the Go language does not support inheritance, but the Go interface fully supports embedding. In embedding, an interface can embed other interfaces or an interface can embed other interface's method signatures in it, the result of both is the same as shown in Example 1 and 2.
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
Extending InterfacesAn interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. The following Sports interface is extended by Hockey and Football interfaces.
Yes, we can do it. An interface can extend multiple interfaces in Java.
You can embed interface types. See the Interface type specification
type Student interface {
People
GetScore() int
GetSchoolName() string
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With