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

时间:2018-02-06 13:12:51

标签: go interface

我有一个Go界面:

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

现在我想要另一个界面Student

1

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

但我不想写复制函数GetNameGetAge

有没有办法避免在GetName界面中写GetAgeStudent?喜欢:

2

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

2 个答案:

答案 0 :(得分:12)

您可以嵌入界面类型。请参阅Interface type specification

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

答案 1 :(得分:0)

这是关于接口扩展的完整示例:

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