当前位置:网站首页>Embedded struct and embedded interface

Embedded struct and embedded interface

2022-06-21 12:10:00 attempt_ to_ do

The embedded struct

When anonymous field is a struct When , So this struct All fields owned are implicitly introduced into the currently defined struct.


package main
import "fmt"
type Human struct {
    
    name string
    age int
    weight int
}
type Student struct {
    
    Human  //  Anonymous field , So default Student contains Human All fields of 
    speciality string
}
func main() {
    
    //  We initialize a student 
    mark := Student{
    Human{
    "Mark", 25, 120}, "Computer Science"}
    //  We go to the corresponding fields 
    fmt.Println("His name is ", mark.name)
    fmt.Println("His age is ", mark.age)
    fmt.Println("His weight is ", mark.weight)
    fmt.Println("His speciality is ", mark.speciality)
    //  Modify the corresponding notes 
    mark.speciality = "AI"
    fmt.Println("Mark changed his speciality")
    fmt.Println("His speciality is ", mark.speciality)
    //  Modify his age information 
    fmt.Println("Mark become old")
    mark.age = 46
    fmt.Println("His age is", mark.age)
    //  Modify his weight information 
    fmt.Println("Mark is not an athlet anymore")
    mark.weight += 60
    fmt.Println("His weight is", mark.weight)
}

The embedded interface

Go What's really fascinating about it is its built-in logic and Syntax , It's like we're learning Struct Anonymous fields learned when , How elegant , So the same logic is introduced to interface Inside , That's not more perfect . If one interface1 As interface2 An embedded field of , that interface2 Implicit inclusion interface1 Inside method.

We can see the source package container/heap There is such a definition in it


type Interface interface {
    
    sort.Interface // Embed fields sort.Interface
    Push(x interface{
    }) //a Push method to push elements into the heap
    Pop() interface{
    } //a Pop elements that pops elements from the heap
}

We see sort.Interface It's actually embedded fields , hold sort.Interface All of the method Implicit inclusion . That is to say, the following three methods :


type Interface interface {
    
    // Len is the number of elements in the collection.
    Len() int
    // Less returns whether the element with index i should sort
    // before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}
原网站

版权声明
本文为[attempt_ to_ do]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211159571614.html