golang 接口类型多态

2019-10-31  本文已影响0人  韩小禹
type stockPosition struct{
    ticker string
    sharePrice float32
    count float32
}

type car struct {
    make string
    model string
    price float32
}

func (c car) getValue() float32 {
    return c.price
}

func (s stockPosition) getValue() float32{
    return s.sharePrice * s.count
}

type valualbe interface {
    getValue() float32
}

/**
公用方法打印传入的类型的信息,为了确保所有struct都有一个指定的方法,就要通过定义接口去规定,同一种类型在不同的实例上似乎表现出不同的行为
同一种类型:var v valuable
在不同的实例上:car{}, stockPosition{}
表现出不同的行为:showValue(c), showValue(s)
 */
func showValue(asset valualbe){
    fmt.Printf("value of the asset is %f\n", asset.getValue())
}

func main(){

    var c valualbe = car{"AUDI","R8", 1900000}
    showValue(c)

    var s valualbe = stockPosition{"GOOG", 577.20, 4}
    showValue(s)
}

#value of the asset is 1900000.000000
#value of the asset is 2308.800049
上一篇 下一篇

猜你喜欢

热点阅读