golang 面向对象
method的语法如下: func (r ReceiverType) funcName(parameters) (results) 下面我们用最开始的例子用method来实现: package main import ( "fmt" "math" ) type Rectangle struct { width,height float64 } type Circle struct { radius float64 } func (r Rectangle) area() float64 { return r.width*r.height } func (c Circle) area() float64 { return c.radius * c.radius * math.Pi } func main() { r1 := Rectangle{12,2} r2 := Rectangle{9,4} c1 := Circle{10} c2 := Circle{25} fmt.Println("Area of r1 is: ",r1.area()) fmt.Println("Area of r2 is: ",r2.area()) fmt.Println("Area of c1 is: ",c1.area()) fmt.Println("Area of c2 is: ",c2.area()) } 在使用method的时候重要注意几点
图示如下:
图2.9 不同struct的method不同 在上例,method area() 分别属于Rectangle和Circle, 于是他们的 Receiver 就变成了Rectangle 和 Circle,或者说,这个area()方法 是由 Rectangle/Circle 发出的。
那是不是method只能作用在struct上面呢?当然不是咯,他可以定义在任何你自定义的类型、内置类型、struct等各种类型上面。这里你是不是有点迷糊了,什么叫自定义类型,自定义类型不就是struct嘛,不是这样的哦,struct只是自定义类型里面一种比较特殊的类型而已,还有其他自定义类型申明,可以通过如下这样的申明来实现。 type typeName typeLiteral 请看下面这个申明自定义类型的代码 type ages int type money float32 type months map[string]int m := months { "January":31,"February":28,... "December":31,} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |