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

lin*_*bin 1 interface go

我有一个Go界面:

type People interface {
    GetName() string
    GetAge() string
}
Run Code Online (Sandbox Code Playgroud)

现在我想要另一个界面Student:

1.

type Student interface {
    GetName() string
    GetAge() string
    GetScore() int
    GetSchoolName() string
}
Run Code Online (Sandbox Code Playgroud)

但我不想写重复的函数GetNameGetAge.

有没有一种方法,以避免写入GetNameGetAgeStudent界面?喜欢:

2.

type Student interface {
    People interface
    GetScore() int
    GetSchoolName() string
}
Run Code Online (Sandbox Code Playgroud)

lin*_*bin 15

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

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())
}
Run Code Online (Sandbox Code Playgroud)

  • 当有像这里给出的完整示例时,它会很有帮助。 (2认同)

Jim*_*imB 13

您可以嵌入接口类型.请参阅接口类型规范

type Student interface {
    People
    GetScore() int
    GetSchoolName() string
}
Run Code Online (Sandbox Code Playgroud)