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
}
You can embed interface types. See the Interface type specification
type Student interface {
People
GetScore() int
GetSchoolName() string
}
This is a full example about interface extend:
package main
import (
"fmt"
)
type People interface {
GetName() string
GetAge() int
}
type Student interface {
People
GetScore() int
GetSchool() string
}
type StudentImpl struct {
name string
age int
score int
school string
}
func NewStudent() Student {
var s = new(StudentImpl)
s.name = "Jack"
s.age = 18
s.score = 100
s.school = "HighSchool"
return s
}
func (a *StudentImpl) GetName() string {
return a.name
}
func (a *StudentImpl) GetAge() int {
return a.age
}
func (a *StudentImpl) GetScore() int {
return a.score
}
func (a *StudentImpl) GetSchool() string {
return a.school
}
func main() {
var a = NewStudent()
fmt.Println(a.GetName())
fmt.Println(a.GetAge())
fmt.Println(a.GetScore())
fmt.Println(a.GetSchool())
}