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,
     }
    }
  • 相关阅读:
    ng-深度学习-课程笔记-1: 介绍深度学习(Week1)
    java发送http请求和多线程
    Spring Cloud Eureka注册中心(快速搭建)
    Spring boot集成Swagger2,并配置多个扫描路径,添加swagger-ui-layer
    springboot在idea的RunDashboard如何显示出来
    Oracle 中select XX_id_seq.nextval from dual 什么意思呢?
    mysql类似to_char()to_date()函数mysql日期和字符相互转换方法date_f
    MySQL的Limit详解
    HikariCP 个人实例
    NBA-2018骑士季后赛
  • 原文地址:https://www.cnblogs.com/VingB2by/p/11073853.html
Copyright © 2011-2022 走看看