cxfans
4/3/2019 - 4:16 AM

golang的指针在struct中的应用区别

golang的指针在struct中的应用区别

package main

import (
	"fmt"
)

type User struct {
	username string
	password string
	age int32
}

func (user User) Set1() {
	user.username = "changed"
}

func (user *User) Set2() {
	user.username = "changed"
}


// 带指针的struct函数可修改struct实例,而不带指针的函数只是对实例的拷贝进行操作
func main() {
	user1 := User{"root", "root", 18}
	user1.Set1()
	fmt.Println("user", user1.username)

	user2 := User{"root", "root", 18}
	user2.Set2()
	fmt.Println("user", user2.username)
}