zoukankan      html  css  js  c++  java
  • 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 ",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的参数时,函数外部同样修改参数生效。

  • 相关阅读:
    0x00000090 该内存不能read written
    AutoCAD系统变量:EDGEMODE
    AutoCAD.net: DoubleClick
    Access 类型转换函数
    无法更改文件夹的隐藏属性 解决方法!
    Windows防火墙无法启动解决办法
    AutoCAD.net: DrawOrderChange display order of the entities in the drawing
    C#调用C++编写的COM DLL
    编辑AutoCAD 2010中新出现的CUIx文件[转]
    hook钩子
  • 原文地址:https://www.cnblogs.com/forgo/p/13259742.html
Copyright © 2011-2022 走看看