为什么带“值接收器”的方法与“指针调用者”一起工作?

时间:2018-05-16 04:24:18

标签: go

我是 Go 的新手。我正在阅读方法接收器。

并且有点混淆为什么值接收器接受指针类型,并且在下面的示例中,即使使用指针类型,名称也没有改变。

我得到了这个结果:

Employee name: Mark Andrew
Employee name: Mark Andrew
Employee name: Mark Andrew

package main

import (
	"fmt"
)

type Employee struct {
	name string
	age  int
}

/*
Method with value receiver
*/
func (e Employee) changeName(newName string) {
	e.name = newName
}

/*
Method with pointer receiver
*/
func (e *Employee) changeAge(newAge int) {
	e.age = newAge
}

func main() {
	e := Employee{
		name: "Mark Andrew",
		age:  50,
	}
	
	// this work perfectly
	fmt.Printf("Employee name: %s", e.name)
	e.changeName("Michael Andrew")
	
	// ofcourse, the name isn't changed => good
	fmt.Printf("\nEmployee name: %s", e.name)
	
	// but why this work too?
	// and why the name wasn't changed? => confused ...
	(&e).changeName("Hallo")
	fmt.Printf("\nEmployee name: %s", e.name)
}

0 个答案:

没有答案