go语言中struct结构体的使用

栏目: Go · 发布时间: 6年前

内容简介:1、struct声明:2、struct 中字段访问:和其他语言一样,使用点例子

一、struct的特点

  • 1、用来自定义复杂数据结构
  • 2、struct里面可以包含多个字段(属性)
  • 3、struct类型可以定义方法,注意和函数的区分
  • 4、struct类型是值类型
  • 5、struct类型可以嵌套
  • 6、 GO 语言没有class类型,只有struct类型

二、struct的定义

1、struct声明:

type 标识符 struct {
    Name string
    Age int
    Score int
}

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

例子

type Student struct {
    Name string
    Age int
    Score int
}

func main(){
    var stu Student
    stu.Name = "lilei"
    stu.Age = 22
    stu.Score = 20
    fmt.Printf("name=%s age=%d score=%d",stu.Name,stu.Age,stu.Score)
}

3、struct定义的三种形式:

a: var stu Student

b:var stu

Student = new(Student)

Student = &Student{}

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

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

三、struct的初始化

1、struct的内存布局:struct中的所有字段在内存是连续的,布局如下:

type Rect1 struct { Min, Max point}

type Rect2 struct { Min, Max *point}

2、链表定义

type School struct {
    Name School
    Next *School
}

每个节点包含下一个节点的地址,这样把所有的节点串起来,通常把链表的第一个节点叫做链表头

3、双链表定义

type School struct {
    Name string
    Next *School
    Prev *School
}

如果有两个指针分别指向前一个节点和后一个节点叫做双链表。

4、二叉树定义

type School struct {

Name string

Left

School

School

}

如果每个节点有两个指针分别用来指向左子树和右子树,我们把这样的结构叫做二叉树

四、特殊自处

1、结构体是用户单独定义的类型,不能和其他类型进行强制转换

2、golang中的struct没有构造函数,一般可以使用工厂模式来解决这个问题

package model
type student struct {
  Name string
  Age int
}
 func NewStudent(name string,age int) *student {
  return &student{
    Name:name,
    Age:age,
  }
}
package main
S := new(student)
S := model.NewStudent("tom",20)

3、我们可以为struct中的每个字段,写上一个tag。这个tag可以通过反射的机制获取到,最常用的场景就是json序列化和反序列化。

type student struct {
  Name string `json="name"`
  Age string `json="age"`
}

4、结构体中字段可以没有名字,即匿名字段

type Car struct {
  Name string
  Age int
}

type Train struct {
  Car
  Start time.Time
  int
}

5、匿名字段的冲突处理

type Car struct {
  Name string
  Age int
}
type Train struct {
  Car
  Start time.Time
  Age int
}

type A struct {
  a int
}
type B struct {
  a int
  b int
}
type C struct {
  A
  B
}

以上所述就是小编给大家介绍的《go语言中struct结构体的使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git (Second Edition)

Pro Git (Second Edition)

Scott Chacon、Ben Straub / Apress / 2014-11-9 / USD 59.99

Scott Chacon is a cofounder and the CIO of GitHub and is also the maintainer of the Git homepage ( git-scm.com ) . Scott has presented at dozens of conferences around the world on Git, GitHub and the ......一起来看看 《Pro Git (Second Edition)》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具