结构体(Struct)

Go中struct的特点

  • 1. 用来自定义复杂数据结构

  • 2. struct里面可以包含多个字段(属性)

  • 3. struct类型可以定义方法,注意和函数的区分

  • 4. struct类型是值类型

  • 5. struct类型可以嵌套

  • 6. Go语言没有class类型,只有struct类型

  • 7. Go语言中有tag

一、struct的定义

1.struct的声明

type 标识符 struct {
       field1 type
       field2 type
}  

例子

type Student struct {
       Name string
       Age int
Score int
}

2. struct中的tag

Tag是结构体中某个字段别名, 可以定义多个, 空格分隔

type Student struct {
    Name string `ak:"av" bk:"bv" ck:"cv"`
}

使用空格来区分多个tag,所以格式要尤为注意


tag相当于该字段的一个属性标签, 在Go语言中, 一些包通过tag来做相应的判断

举个例子, 比如我们有一个结构体

type Student struct {
    Name string
}

然后我们将一个该结构体实例化一个 s1

s1 := Student{
        Name: "s1",
    }

再将 s1 序列化

v, err := json.Marshal(s1) // json.Marshal方法,json序列化,返回值和报错信息
if err != nil { // 不为nil代表报错
    fmt.Println(err)
}
fmt.Println(string(v)) // []byte转string, json

此时 string(v) 为 

{
  "Name": "s1"  
}

因为在 Go 语言中, 结构体字段要想为外部所用就必须首字母大写, 但是如果这个 s1 是返回给前端的, 那每个字段都首字母大写就很怪, 此时我们可以给 Student 加tag解决

结构体修改为

type Student struct {
    Name string`json:"name"`
}

序列化时, 会自己找到名为 json 的tag, 根据值来进行json后的赋值

因此 string(v) 为

{
  "name": "s1"  
}


  • json json序列化或反序列化时字段的名称
  • db sqlx模块中对应的数据库字段名
  • form gin框架中对应的前端的数据字段名
  • binding 搭配 form 使用, 默认如果没查找到结构体中的某个字段则不报错值为空, binding为 required 代表没找到返回错误给前端 

3. struct 中字段访问:和其他语言一样,使用点  

var stu Student

stu.Name = “tony”
stu.Age = 18
stu.Score=20

fmt.Printf(“name=%s age=%d score=%d”, stu.Name, stu.Age, stu.Score

4.  struct定义的三种形式:

a. var stu Student
b. var stu *Student = new (Student)
c. var stu *Student = &Student{}

其中b和c返回的都是指向结构体的指针,访问形式如下:

stu.Name、stu.Age和stu.Score或者 (*stu).Name、(*stu).Age等

例子

package main

import "fmt"

type Student struct {
    Name  string
    Age   int32
    score float32 // 外部的包访问不了这个字段
}

func main() {
    // 结构体的三种定义方式
    // 方式一
    var stu Student
    stu.Name = "zhangyafei"
    stu.Age = 24
    stu.score = 88

    fmt.Printf("Name: %p\n", &stu.Name) // string占10字节
    fmt.Printf("Age: %p\n", &stu.Age)   // int占8字节  int32占4字节
    fmt.Printf("score: %p\n", &stu.score)

    // 方式二
    var stu1 *Student = &Student{
        Age:  20,
        Name: "ZhangYafei",
    }
    fmt.Println(stu1)
    fmt.Println(stu1.Name)

    // 方式三
    var stu2 = Student{
        Age:  20,
        Name: "Fei",
    }
    fmt.Println(stu2)
    fmt.Println(stu2.Age)

}

// Name: 0xc000004460
// Age: 0xc000004470
// score: 0xc000004478

// Age int32
// Name: 0xc000050400
// Age: 0xc000050410
// score: 0xc000050414
// &{ZhangYafei 20 0}
// {Fei 20 0}
struct的定义示例

相关文章: