zoukankan      html  css  js  c++  java
  • 从零开始学Go之基本(五):结构体

    结构体:

    声明:

    type 结构体名 struct{
    ​
     结构体内部字段
    ​
    }

    例子:

    type UserInfo struct {
     Id    string `json:"id"`
     Name   string `json:"name"`
     Headpicture string `json:"headpicture"`
     Info   string `json:"info"`
    }

    实例化:

    package main
    ​
    import "fmt"
    ​
    type Vertex struct {
     X, Y int
    }
    ​
    var v Vertex // 创建一个 Vertex 类型的结构体
    var (
     v1 = Vertex{1, 2} // 创建一个 Vertex 类型的结构体并显式赋值
     v2 = Vertex{X: 1} // Y:0 被隐式地赋予,即默认值
     v3 = Vertex{}  // X:0 Y:0
     p = &Vertex{1, 2} // 创建一个 *Vertex 类型的结构体(指针)
    )
    ​
    func main() {
     v.X = 3
     v.Y = 3
     fmt.Println(v, v1, v2, v3, p)
    }

    运行结果

    {3 3} {1 2} {1 0} {0 0} &{1 2}

    new关键字:

    可以使用 new 关键字对类型(包括结构体、整型、浮点数、字符串等)进行实例化,结构体在实例化后会形成指针类型的结构体

    type Vertex struct {
     X, Y int
    }
    ​
    func main() {
     i := new(int)//创建一个int指针
     v := new(Vertex)//相当于v = &Vertex{},创建一个Vertex结构体指针
     v.X = 3
     fmt.Println(i, v, &v)
    }

    运行结果

    0xc04204e080 &{3 0} 0xc04206c018

    取地址实例化:

    由于 变量名 = &结构体名{} 的方式是实例化一个结构体指针,这时候可以通过指针的方式来对结构体实例化的同时进行赋值。

    type Vertex struct {
     X, Y int
    }
    ​
    func NewVertex(X,Y int)*Vertex {//封装实例化过程
     return &Vertex{
      X: X,
      Y: Y,
     }
    }
    ​
    func main() {
     v1 := new(Vertex)
     v2 := &Vertex{}
     v := &Vertex{
      X:3,//可以利用键值对来只对一个值进行赋值
     }
     v1 = v
     v2 = NewVertex(8,9)
     fmt.Println(v1, v2)
    }

    运行结果

    &{3 0} &{8 9}

    构造函数:

    在C中的构造函数是与原结构体同名,但参数不同的重载函数完成,但Go中只能通过模拟这一特性完成构造函数,即通过多个不重名函数通过取地址实例化完成。

    type Vertex struct {
     X, Y int
    }
    ​
    func NewVertexX(X int)*Vertex {
     return &Vertex{
      X: X,
     }
    }
    ​
    func NewVertexY(Y int)*Vertex {
     return &Vertex{
      Y: Y,
     }
    }
    ​
    func NewVertex(X,Y int)*Vertex {
     return &Vertex{
      X: X,
      Y: Y,
     }
    }
  • 相关阅读:
    php数组gbk和utf8的相互转化
    【原创】SSRS (SQL Serve Reporting Service) 访问权限的问题
    【原创】软件开发项目管理总结
    【原创】Team Foundation Server 域环境迁移
    【转载】 C#中数组、ArrayList和List三者的区别
    【转载】NuGet镜像上线试运行
    【原创】 关于全局静态变量初始化
    【转载】Fiddler进行模拟Post提交json数据,总为null解决方式
    【转载】解决Windows 10 局域网内共享的问题
    【原创】 查看端口号被占用
  • 原文地址:https://www.cnblogs.com/VingB2by/p/11073853.html
Copyright © 2011-2022 走看看