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

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.

主站蜘蛛池模板: 吉木乃县| 山阳县| 双鸭山市| 永嘉县| 通辽市| 台北市| 青河县| 冷水江市| 水富县| 湘潭县| 肥城市| 淮南市| 鄂托克旗| 汽车| 昭通市| 信丰县| 神木县| 浙江省| 绥宁县| 本溪| 佛冈县| 合阳县| 两当县| 桦川县| 宁远县| 迭部县| 陈巴尔虎旗| 岗巴县| 贵德县| 本溪| 北碚区| 旬邑县| 察哈| 志丹县| 营山县| 江口县| 吴忠市| 佳木斯市| 锡林郭勒盟| 临澧县| 宜阳县|