Table of Contents
Structure inheritance" >Structure inheritance

" >BMW Car

" >BYD car
main代码" >main代码
执行结果
" >执行结果
序列化" >序列化
切片序列化" >切片序列化
map序列化
" >map序列化
结构体序列化" >结构体序列化
结构体代码" >结构体代码
main
" >main
切片套结构体
" >切片套结构体
结构体标签(Tag)
" >结构体标签(Tag)
Summary" >Summary
Home Backend Development Golang Structure of the basics of Go language (winter)

Structure of the basics of Go language (winter)

Jul 24, 2023 pm 05:29 PM
go language

Structure inheritance

Speaking of inheritance, anyone who has studied Java must be familiar with Python. , but there is no such thing in Go.

What should we do???, we still have to use a structure to achieve it.

Pretend that we are all boys and like cars, so let’s take cars as an example.


##Car structure

//车
type Car struct {
    Brand  string //车品牌
    CarNum string //车牌号
    Tyre   int    //轮胎个数
}


//给车绑定一个方法,说明车的基本信息
func (this *Car) carInfo() {
    fmt.Printf("品牌:%s,车牌号:%s,轮胎个数:%d\n", this.Brand, this.CarNum, this.Tyre)
}
Copy after login

BMW Car

//宝马车
type BMWCar struct {
    //*Car和Car基本没有区别,一个存的是整个结构体,一个存的是结构体地址,用法大同小异
    *Car //这就表示继承了Car这个结构体
}
Copy after login

BYD car

//比亚迪车
type BYDCar struct {
    *Car
}
Copy after login

may be seen You will feel familiar with this. Isn't this the nested structure we used in the previous lesson? ? ?

Does this have anything to do with inheritance?

其实在Go中,结构体既可以用来存储数据,也可以用来模仿对象的各种操作。

main代码

func main() {
    //一个宝马对象
    var bmw1 = BMWCar{&Car{
        Brand:  "宝马x8",
        CarNum: "京666",
        Tyre:   4,
}}
    //一个比亚迪对象
    var byd1 = BYDCar{&Car{
        Brand:  "比亚迪L3",
        CarNum: "京111",
        Tyre:   4,
}}
    //因为 BMWCar 和 BYDCar 都继承了Car,所以都有carInfo这个方法
    bmw1.carInfo()
    byd1.carInfo()
}
Copy after login

执行结果

Structure of the basics of Go language (winter)

这就是一个最简单的,面向对象,跟其他语言一样,继承会将所有的属性和方法都继承过来。


序列化

到此为止呢,结构体基本可以告一段落了,基本算是入门了,当然,并没有结束,但是我想大家都累了,换个方向继续玩。

这个东西叫做序列化,什么意思呢,就是像咱们的切片了,map了,结构体了等,这些都是Go的类型。

如果要和其他语言交流,人家可没有这些玩意唉,那怎么办呢???

众多大佬就形成了一个规范,json数据格式,json数据必须是字符串类型

最外面是'号,键/值对组合中的键名写在前面并用双引号""包裹。

就像这样。

'{"Gender":"男","Name":"张三"}'    //'说明这个是字符串,一般打印时不显示
Copy after login

序列化我们用到的是json模块的Marshal方法。


切片序列化

单独的切片序列化用的很少,但是仍然还是要知道。

示例代码

package main


import (
    "encoding/json"
    "fmt"
)


type Student struct {
    Gender string
    Name   string
}


func main() {
    var StudentList = []string{"张三", "李四"}
    fmt.Printf("StudentList类型:%T\n", StudentList) //[]string,这是列表类型
    serializeByte, err := json.Marshal(StudentList)
    if err != nil {
        fmt.Println("序列化失败")
        return
}
    var serializeStr = string(serializeByte)
    fmt.Printf("serializeStr类型:%T\n", serializeStr) //string,这是字符串类型
    fmt.Printf("serializeStr值:%v\n", serializeStr) //["张三","李四"]
}
Copy after login

第16行代码将切片序列化,但是返回的是[]byte类型,第21行代码将[]byte类型转成字符串。

执行结果

Structure of the basics of Go language (winter)


map序列化

字典序列化,就比较有味道了,序列化的是一个标准的json数据格式。

示例代码

package main


import (
    "encoding/json"
    "fmt"
)


type Student struct {
    Gender string
    Name   string
}


func main() {
    var StudentInfo = map[string]string{
        "Name":"张三",
        "Age":"18",
        "Gender":"男",
}
    fmt.Printf("StudentInfo类型:%T\n",StudentInfo)
    serializeByte, err := json.Marshal(StudentInfo)
    if err != nil {
        fmt.Println("序列化失败")
}
    var serializeStr = string(serializeByte)
    fmt.Printf("serializeStr类型:%T\n", serializeStr) //string,这是字符串类型
    fmt.Printf("serializeStr值:%v\n", serializeStr) //{"Age":"18","Gender":"男","Name":"张三"}
}
Copy after login

执行结果

Structure of the basics of Go language (winter)

这个就有点像标准的json格式了。


结构体序列化

结构体代码

type Student struct {
    Name   string
    Gender string
    Age    int
}
Copy after login

main

func main() {
  var s1 = Student{
    Name:   "张三",
    Gender: "男",
    Age:    18,
  }
  fmt.Printf("StudentInfo类型:%T\n", s1)
  serializeByte, err := json.Marshal(s1)
  if err != nil {
    fmt.Println("序列化失败")
  }
  var serializeStr = string(serializeByte)
  fmt.Printf("serializeStr类型:%T\n", serializeStr) //string,这是字符串类型
  fmt.Printf("serializeStr值:%v\n", serializeStr)
}
Copy after login

执行结果

Structure of the basics of Go language (winter)


切片套结构体

一般情况下,这种方式数据格式是用的比较多的。

当然, 还可以切片嵌套map,方法和此方法一样,不做例子了。

示例代码

package main


import (
  "encoding/json"
  "fmt"
)


type Student struct {
  Name   string
  Gender string
  Age    int
}


func main() {
  var s1 = Student{
    Name:   "张三",
    Gender: "男",
    Age:    18,
  }
  var s2 = Student{
    Name:   "李四",
    Gender: "女",
    Age:    16,
  }
  //一个存放 Student 的列表
  var studentList = []Student{s1, s2}
  fmt.Printf("StudentInfo类型:%T\n", studentList)
  serializeByte, err := json.Marshal(studentList) //main.Student
  if err != nil {
    fmt.Println("序列化失败")
  }
  var serializeStr = string(serializeByte)
  fmt.Printf("serializeStr类型:%T\n", serializeStr) //string,这是字符串类型
  fmt.Printf("serializeStr值:%v\n", serializeStr)  
}
Copy after login

执行结果

Structure of the basics of Go language (winter)


结构体标签(Tag)

Tag可以理解为结构体的说明,由一对反引号包裹起来。

但是一般情况下,Tag在序列化是用的比较多。


结构体代码

type Student struct {
  Name   string `json:"name"`
  Gender string `json:"gender"`
  Age    int    `json:"age"`
}
Copy after login

每个字段后面跟的,就是Tag,一定不要把格式搞错啦。

main代码

func main() {
  var s1 = Student{
    Name:   "张三",
    Gender: "男",
    Age:    18,
  }
  fmt.Printf("StudentInfo类型:%T\n", s1)
  serializeByte, err := json.Marshal(s1) //main.Student
  if err != nil {
    fmt.Println("序列化失败")
  }
  var serializeStr = string(serializeByte)
  fmt.Printf("serializeStr类型:%T\n", serializeStr) //string,这是字符串类型
  fmt.Printf("serializeStr值:%v\n", serializeStr)  
}
Copy after login

执行结果

Structure of the basics of Go language (winter)

可以发现key成小写的了,这就说明一个问题。

During serialization, if the structure has jsonThis Tag will be serialized based on jsonTag. If there is no jsonTag, the structure field shall prevail.


Summary

Above we have learned the basic structure of Go Structure inheritance,Serialization,Structure tag. After learning Go's structure, you may also know how to imitate object-oriented in Go.

The above is the detailed content of Structure of the basics of Go language (winter). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles