您的位置:首页 > 编程语言 > Go语言

Go语言学习之method(The way to go)

2017-04-12 01:24 661 查看
生命不止,继续go go go !

在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())
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: