您的位置 首页 golang

go语言结构体

结构体的定义:

 type identifier struct {
    field1 type1
    field2 type2
    ...
}  

结构体初始化以及使用

结构体的两种初始化方式:

 package main

import "fmt"

type Students struct {
Name string 
Age int
}
func main() {
student:=new(Students)
student.Name="tom"
student.Age=18
student2:=Students{
Name: "leo",
Age: 17,
}
fmt.Println(student)
fmt.Println(student2)
}
  

运行结果:

定义一个狗的结构体并实现狗的方法

 package main

import "fmt"

type Dog struct {
Name string
}

func (c *Dog) Run()  {
fmt.Println(c.Name+"正在跑")
}
func (c *Dog) DogBarks()  {
fmt.Println(c.Name+":汪汪汪")
}
func main() {
tom:=new(Dog)
tom.Name="tom"
tom.Run()
tom.DogBarks()
}
  

执行结果:

带标签的结构体和不带标签的结构体

回到学生的例子

 package main

import (
"encoding/json"
"fmt"
)

type Students struct {
Name string
Age int
}
func main() {
student:=new(Students)
student.Name="tom"
student.Age=18
jsonStr,err:=json.Marshal(student)
if err!=nil{
panic(err)
}
fmt.Println(string(jsonStr))
}
  

执行结果:

我们可以看到不带标签转化出来的json是大驼峰的,但是我们常用的json显然不是这样的

现在我们尝试带上标签

 package main

import (
"encoding/json"
"fmt"
)

type Students struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
student:=new(Students)
student.Name="tom"
student.Age=18
jsonStr,err:=json.Marshal(student)
if err!=nil{
panic(err)
}
fmt.Println(string(jsonStr))
}
  

执行结果:

结构体的内嵌

我们在上面的基础上我们在新建一个学校的结构体,那么我们这个学生属于那个学校

 package main

import (
"fmt"
)

//学校结构体
type School struct {
SchoolName string `json:"school_name"`
}
//学生结构体
type Students struct {
Name string `json:"name"`
Age int `json:"age"`
School
}

func (c *Students)Info()  {
info:=fmt.Sprintf("我是%s的学生,我叫%s,我今年%d岁",c.SchoolName,c.Name,c.Age)
fmt.Println(info)
}
func main() {
//创建一个学生
student:=new(Students)
student.Name="tom"
student.Age=18
//创建一个学校
school:=new(School)
school.SchoolName="中华小学"
student.School=*school
student.Info()
}
  

执行结果:

文章来源:智云一二三科技

文章标题:go语言结构体

文章地址:https://www.zhihuclub.com/101376.shtml

关于作者: 智云科技

热门文章

网站地图