【问题标题】:How to extend a Go interface to another interface?如何将 Go 接口扩展到另一个接口?
【发布时间】:2018-07-16 13:38:48
【问题描述】:

我有一个 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
}

【问题讨论】:

    标签: go interface


    【解决方案1】:

    您可以嵌入接口类型。见Interface type specification

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 如果有一个像这里给出的完整示例,它会很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2011-11-13
      相关资源
      最近更新 更多