如何将Go接口扩展到另一个接口?

30

我有一个Go接口:

type People interface {
    GetName() string
    GetAge() string
}

现在我想要另一个接口 Student:

1.

type Student interface {
    GetName() string
    GetAge() string
    GetScore() int
    GetSchoolName() string
}

但我不想写重复的函数GetNameGetAge

有没有一种方法可以避免在Student接口中编写GetNameGetAge?例如:

2.

type Student interface {
    People interface
    GetScore() int
    GetSchoolName() string
}
2个回答

56

你可以嵌入接口类型。请参阅接口类型规范

type Student interface {
    People
    GetScore() int
    GetSchoolName() string
}

34

这是一个有关接口扩展的完整示例:

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())
}

2
当像这里给出的完整示例一样时,它非常有帮助。 - user12817546

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接