官术网_书友最值得收藏!

Methods 

Let's say we wrote these functions, and we have defined email as before:

 type email string

func check(a email) { ... }
func send(a email, msg string) { ... }

Observe that email is always the first type in the function parameters.

Calling the functions look something like this:

e := "john@smith.com"
check(e)
send(e, "Hello World")

We may want to make that into a method of the email type. We can do so as follows:

type email string

func (e email) check() { ... }
func (e email) send(msg string) { ... }

(e email) is called the receiver of the method.

Having defined the methods thus, we may then proceed to call them:

e := "john@smith.com"
e.check()
e.send("Hello World")

Observe the difference between the functions and methods. check(e) becomes e.check(). send(e, "Hello World") becomes e.send("Hello World"). What's the difference other than syntactic difference? The answer is, not much.

A method in Go is exactly the same as a function in Go, with the receiver of the method as the first parameter of the function. It is unlike methods of classes in object-oriented programming languages.

So why bother with methods? For one, it solves the expression problem quite neatly. To see how, we'll look at the feature of Go that ties everything together nicely: interfaces.

主站蜘蛛池模板: 淅川县| 靖西县| 鄂尔多斯市| 麻栗坡县| 松溪县| 镇沅| 枣庄市| 甘德县| 大丰市| 凌云县| 和硕县| 齐河县| 库尔勒市| 五原县| 南宫市| 阿城市| 安阳县| 濮阳县| 邵武市| 哈尔滨市| 博客| 青铜峡市| 江门市| 余江县| 南康市| 云霄县| 迁安市| 尼木县| 丹江口市| 荆门市| 安溪县| 汉沽区| 梅州市| 鸡西市| 永城市| 韩城市| 濉溪县| 全州县| 嘉荫县| 大新县| 阳曲县|