golang struct函数的参数设置:
实例一:形参和类型都为指针类型
type user struct {
Name string
Age int
}
func (u *user) setUser(a *user) {
a.Name = "fwefew"
fmt.Printf("func => 形参的name:%s
",a.Name)
fmt.Printf("func => struct类型的name:%s
",u.Name)
}
func main() {
u := user{"xiaoming", 13}
u.setUser(&u)
fmt.Printf("main => name:%s
",u.Name)
}
输出:
func => 形参的name:fwefew
func => struct类型的name:fwefew
main => name:fwefew
实例二:形参和类型都为普通类型
type user struct {
Name string
Age int
}
func (u user) setUser(a user) {
a.Name = "fwefew"
fmt.Printf("func => 形参的name:%s
",a.Name)
fmt.Printf("func => struct类型的name:%s
",u.Name)
}
func main() {
u := user{"xiaoming", 13}
u.setUser(u)
fmt.Printf("main => name:%s
",u.Name)
}
输出:
func => 形参的name:fwefew
func => struct类型的name:xiaoming
main => name:xiaoming
实例三:形参为指针类型、类型为普通类型
type user struct {
Name string
Age int
}
func (u user) setUser(a *user) {
a.Name = "fwefew"
fmt.Printf("func => 形参的name:%s
",a.Name)
fmt.Printf("func => struct类型的name:%s
",u.Name)
}
func main() {
u := user{"xiaoming", 13}
u.setUser(&u)
fmt.Printf("main => name:%s
",u.Name)
}
输出:
func => 形参的name:fwefew
func => struct类型的name:xiaoming
main => name:fwefew
实例四:形参为普通类型、类型为指针类型
type user struct {
Name string
Age int
}
func (u *user) setUser(a user) {
a.Name = "fwefew"
fmt.Printf("func => 形参的name:%s
",a.Name)
fmt.Printf("func => struct类型的name:%s
",u.Name)
}
func main() {
u := user{"xiaoming", 13}
u.setUser(u)
fmt.Printf("main => name:%s
",u.Name)
}
输出:
func => 形参的name:fwefew
func => struct类型的name:xiaoming
main => name:xiaoming
总结:形参为指针类型时,在函数类修改struct的参数时,函数外部同样修改参数生效。