Loading

Go Struct之函数参数设置

golang struct函数的参数设置:

实例一:形参和类型都为指针类型


type user struct {
    Name string
    Age  int
}
func (u *user) setUser(a *user) {
    a.Name = "fwefew"
   fmt.Printf("func => 形参的name:%s\n",a.Name)
    fmt.Printf("func => struct类型的name:%s\n",u.Name)
}
func main() {
    u := user{"xiaoming", 13}
    u.setUser(&u)
    fmt.Printf("main => name:%s\n",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\n",a.Name)
    fmt.Printf("func => struct类型的name:%s\n",u.Name)
}

func main() {
    u := user{"xiaoming", 13}
    u.setUser(u)
    fmt.Printf("main => name:%s\n",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\n",a.Name)
    fmt.Printf("func => struct类型的name:%s\n",u.Name)
}

func main() {
    u := user{"xiaoming", 13}
    u.setUser(&u)
    fmt.Printf("main => name:%s\n",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\n",a.Name)
    fmt.Printf("func => struct类型的name:%s\n",u.Name)
}

func main() {
    u := user{"xiaoming", 13}
    u.setUser(u)
    fmt.Printf("main => name:%s\n",u.Name)
}

输出:

func => 形参的name:fwefew
func => struct类型的name:xiaoming
main => name:xiaoming

 

总结:形参为指针类型时,在函数类修改struct的参数时,函数外部同样修改参数生效。

posted @ 2020-07-07 11:21  Allfuture  阅读(591)  评论(0编辑  收藏  举报