go方法定义中的问题

onlyou · · 764 次点击
jan-bar
想要拥有,必定付出。
```go package main import "fmt" type Employee struct { name string salary int } func (e Employee) changeName(newName string) { (e).name = newName } func (e *Employee) changeName1(newName string) { (e).name = newName } func main() { e := Employee{name: "Ross Geller", salary: 1200} // e before name change fmt.Println("e before name change =", e) // create pointer to `e` ep := &e // change name ep.changeName("Monica Geller 1") // e after name change fmt.Println("ep after name change =", e) // change name e.changeName1("Monica Geller 2") // e after name change fmt.Println("e after name change =", e) // change name ep.changeName1("Monica Geller 3") // e after name change fmt.Println("ep after name change =", e) } 结果: e before name change = {Ross Geller 1200} ep after name change = {Ross Geller 1200} e after name change = {Monica Geller 2 1200} ep after name change = {Monica Geller 3 1200} ``` 从上面不难看出changeName和changeName1传递的对象一个是值传递,一个是指针传递 从测试结果来看,e.changeName1是可以正常使用的,在changeName1里面默认用指针操作。
#1