go 關於類型斷言和實現接口的測試

package main

import "fmt"

type LittleBoy struct {
    name string
    age  int32
}

type Boy struct {
    name string
    age  int32
}

type Person interface {
    SayName()
}

func (p Boy) SayName() {
    fmt.Println(p.name)
}

func (p LittleBoy) SayName() {
    fmt.Println(p.name)
}

func main() {
    fmt.Println("hello world!")
    person := LittleBoy{
        name: "cyao",
        age:  18,
    }
    ExecSayName(person)
}

func ExecSayName(person Person) {
    person2, ok := person.(LittleBoy)
    if ok {
        person2.name = "cyao2"
    }
    person = person2
    person.SayName()
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章