Go语言学习之method(The way to go)
2017-04-12 01:24
661 查看
生命不止,继续go go go !
在golang的世界中,一定要区分 方法和函数。
Go中没有类的概念,但是我们可以在一些类型上定义一些方法,也就是所谓的方法,跟函数不同。
通过func关键字声明方法
方法的使用
方法与函数的区别
方法和函数定义语法区别在于:
方法前置实例接受参数,这个receiver可以是基础类型也可以是指针。
receiver传值和传指针的区别
对于下面的代码,没有什么区别:
那到底有什么区别呢?这时候方法集要出场了!!!
类型*T方法集包含所有receiver T + *T 方法
在golang的世界中,一定要区分 方法和函数。
Go中没有类的概念,但是我们可以在一些类型上定义一些方法,也就是所谓的方法,跟函数不同。
通过func关键字声明方法
type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) }
type X struct{} func (x *X) test(){ println("hi!", x) }
方法的使用
func main() { v := Vertex{3, 4} fmt.Println(v.Abs()) }
方法与函数的区别
方法和函数定义语法区别在于:
方法前置实例接受参数,这个receiver可以是基础类型也可以是指针。
func (d *duck) quack() { // receiver // do something } func quack(d *duck) { // funciton argument // do something }
receiver传值和传指针的区别
对于下面的代码,没有什么区别:
package main import "fmt" type Rectangle struct { length, width int } func (r Rectangle) Area_by_value() int { return r.length * r.width } func (r *Rectangle) Area_by_reference() int { return r.length * r.width } func main() { r1 := Rectangle{4, 3} fmt.Println("Rectangle is: ", r1) fmt.Println("Rectangle area is: ", r1.Area_by_value()) fmt.Println("Rectangle area is: ", r1.Area_by_reference()) fmt.Println("Rectangle area is: ", (&r1).Area_by_value()) fmt.Println("Rectangle area is: ", (&r1).Area_by_reference()) }
那到底有什么区别呢?这时候方法集要出场了!!!
类型*T方法集包含所有receiver T + *T 方法
package main import ( "fmt" ) type IFace interface { SetSomeField(newValue string) GetSomeField() string } type Implementation struct { someField string } func (i *Implementation) GetSomeField() string { return i.someField } func (i *Implementation) SetSomeField(newValue string) { i.someField = newValue } func Create() *Implementation { return &Implementation{someField: "Hello"} } func main() { var a IFace a = Create() a.SetSomeField("World") fmt.Println(a.GetSomeField()) }
相关文章推荐
- Go语言学习之encoding/xml(The way to go)
- Go语言学习之archive/zip、compress/zlib、compress/gzip包(the way to go)
- Go语言学习之运算符(The way to go)
- Go语言学习之log包(The way to go)
- Go语言学习之Arrays和Slices (The way to go)
- Go语言学习之bufio包(The way to go)
- Go语言学习之ioutil包(The way to go)
- Go语言学习之map (The way to go)
- Go语言学习之net包(The way to go)
- Go语言学习之encoding/json包(The way to go)
- Go语言学习之encoding/gob包(The way to go)
- Go语言学习之变量(The way to go)
- Go语言学习之指针(The way to go)
- Go语言学习之time包(获取当前时间戳等)(the way to go)
- Go语言学习之Hello World(The way to go)
- Go语言学习之常量(The way to go)
- Go语言学习之常量(The way to go)
- Go语言学习之interface(The way to go)
- Go语言学习之字符串(The way to go)
- Go语言学习之flag包(The way to go)