多态就是多重形态。
案例:
收入的案例:
package main import ( "fmt" ) type Income interface { calculate () float64 source() string } //固定账单项目 type FixedBuilding struct { ProjectName string biddedAcount float64 } // 定时和材料项目 type TimeAndMetiarl struct { ProjectName string WorkHours int64 WorkRate float64 } func (f FixedBuilding)calculate() float64 { return f.biddedAcount } func (f FixedBuilding)source() string { return f.ProjectName } //通过广告点击获得收入 type Advertise struct { dName string Clickout int incomePerclick float64 } func (a Advertise)calculate() float64 { // a.incomePerclick*a.Clickout return a.incomePerclick*float64(a.Clickout) } func (a Advertise)source() string { return a.dName } func calculateNetIncome(ic []Income)float64 { netIncome :=0.0 for _,v := range ic{ fmt.Printf("收入来源:%s 收入金额:%+v ",v.source(),v.calculate()) netIncome +=v.calculate() } return netIncome } func main() { p1 :=FixedBuilding{ "项目1", 8000, } p2 :=FixedBuilding{ "项目2", 9000, } p3 :=Advertise{ dName: "百度", Clickout: 100, incomePerclick: 60, } p4 :=Advertise{ dName: "谷歌", Clickout: 10, incomePerclick: 80, } ic := []Income{p1,p2,p3,p4} fmt.Println(calculateNetIncome(ic)) }
/* out
收入来源:项目1 收入金额:8000
收入来源:项目2 收入金额:9000
收入来源:百度 收入金额:6000
收入来源:谷歌 收入金额:800
23800
*/