内容纲要

不使用接口的遍历

package main

import "fmt"

type vehicle struct {
    Seats    int
    MaxSpeed int
    Color    string
}

type car struct {
    vehicle
    Wheels int
    Doors  int
}

type plane struct {
    vehicle
    Jet bool
}

type boat struct {
    vehicle
    Length int
}

func main() {
    prius := car{}
    tacoma := car{}
    bmw528 := car{}
    cars := []car{prius, tacoma, bmw528}

    boeing747 := plane{}
    boeing757 := plane{}
    boeing767 := plane{}
    planes := []plane{boeing747, boeing757, boeing767}

    sanger := boat{}
    nautique := boat{}
    malibu := boat{}
    boats := []boat{sanger, nautique, malibu}

    for key, value := range cars {
        fmt.Println(key, " - ", value)
    }

    for key, value := range planes {
        fmt.Println(key, " - ", value)
    }

    for key, value := range boats {
        fmt.Println(key, " - ", value)
    }
}

空接口遍历

package main

import "fmt"

type vehicles interface{}

type vehicle struct {
    Seats    int
    MaxSpeed int
    Color    string
}

type car struct {
    vehicle
    Wheels int
    Doors  int
}

type plane struct {
    vehicle
    Jet bool
}

type boat struct {
    vehicle
    Length int
}

func main() {
    prius := car{}
    tacoma := car{}
    bmw528 := car{}
    boeing747 := plane{}
    boeing757 := plane{}
    boeing767 := plane{}
    sanger := boat{}
    nautique := boat{}
    malibu := boat{}
    rides := []vehicles{prius, tacoma, bmw528, boeing747, boeing757, boeing767, sanger, nautique, malibu}

    for key, value := range rides {
        fmt.Println(key, " - ", value)
    }
}

空接口传参数

package main

import "fmt"

type animal struct {
    sound string
}

type dog struct {
    animal
    friendly bool
}

type cat struct {
    animal
    annoying bool
}

func specs(a interface{}) {
    fmt.Println(a)
}

func main() {
    fido := dog{animal{"woof"}, true}
    fifi := cat{animal{"meow"}, true}
    specs(fido)
    specs(fifi)
}

空接口切片

package main

import "fmt"

type animal struct {
    sound string
}

type dog struct {
    animal
    friendly bool
}

type cat struct {
    animal
    annoying bool
}

func main() {
    fido := dog{animal{"woof"}, true}
    fifi := cat{animal{"meow"}, true}
    shadow := dog{animal{"woof"}, true}
    critters := []interface{}{fido, fifi, shadow}
    fmt.Println(critters)
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注