type Employee struct {
name string
salary int
}
func (e *Employee) changeName(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")
// e after name change
fmt.Println("e after name change =", e)
}
为什么 要 ep := &e,而不是直接 e.changeName 来修改呢,结果不是都 一样吗
```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