Go 在结构体类型中嵌入接口类型 代码示范

4 min read

以下是一个示例代码,它定义了一个结构体类型 Student,其中嵌入了一个接口类型 Person:

package main

import "fmt"

type Person interface {
    GetName() string
    GetAge() int
}

type Student struct {
    name string
    age  int
    Person
}

func (s Student) GetName() string {
    return s.name
}

func (s Student) GetAge() int {
    return s.age
}

func main() {
    s := Student{
        name: "Alice",
        age:  20,
    }
    fmt.Println(s.GetName()) // Output: Alice
    fmt.Println(s.GetAge())  // Output: 20
}

在上面的示例代码中,Student 结构体类型中嵌入了一个 Person 接口类型。因此,Student 类型实现了 Person 接口中的两个方法 GetName() 和 GetAge()。我们可以通过 s.GetName() 和 s.GetAge() 方法来获取 Student 对象的 name 和 age 值。