当前位置:网站首页>Go结构体
Go结构体
2022-07-28 04:05:00 【紫罗兰与海棠】
一、定义结构体
结构体定义需要使用 type 和 struct 语句。struct 语句定义一个新的数据类型,结构体中有一个或多个成员。type 语句设定了结构体的名称。
type struct_variable_type struct {
member definition
member definition
...
member definition
}
type Book struct {
title string
price int
}
二、访问结构体成员
结构体.成员名

三、结构体作为函数参数
func printBook( book Books ) {
fmt.Printf( "Book title : %s\n", book.title)
fmt.Printf( "Book author : %s\n", book.author)
fmt.Printf( "Book subject : %s\n", book.subject)
fmt.Printf( "Book book_id : %d\n", book.book_id)
}
四、结构体指针
定义
var struct_pointer *Book
以上定义的指针变量可以存储结构体变量的地址。查看结构体变量地址,可以将 & 符号放置于结构体变量前
struct_pointer = &Book1
使用结构体指针访问结构体成员,使用 “.” 操作符
struct_pointer.title
四、嵌套结构体
go语言没有嵌套对象思想,也没有继承关系,可以使用结构体嵌套实现这种效果
type Dog struct {
name string
age int
}
type Person struct {
name string
dog Dog
}
dog := Dog{
name: "旺旺",
age: 3,
}
person := Person{
name: "小明",
dog: dog,
}
五、方法
go语言没有面向对象特性,也没有类对象的概念。可以使用结构体来模拟这些特性,可以声明一些方法,属于某个结构体
语法
方法是一种特殊的函数,定义于struct之上,与struct关联绑定,方法就是有接收者的函数
type mytype struct{
}
func(recv mytype) my_method(para) return_type{
}
func(recv *mytype) my_method(para) return_type{
}
- mytype:定义一个结构体
- recv:接收该方法的结构体
- my_method:方法名称、
接收者类型
- 值类型为复制结构体副本
- 指针类型为原结构体本身
边栏推荐
- Detailed explanation of string + memory function (C language)
- Day08 redis的基础知识
- Leetcode58. Length of the last word
- cookie与Session
- Redis cluster
- Monotonous stack -- 42. Receiving rain -- a difficult problem that big factories must know
- Summary of static blog building tools
- 《剑指offer》| 刷题小记
- Istio's Traffic Management API
- Greed 122. The best time to buy and sell stocks II
猜你喜欢

【无标题】

简单、好用的性能测试工具推荐

常用的弱网测试工具

RT-Thread改变打印串口(在BSP的基础上添加其他功能)

STC timer is abnormal (how to modify the initial value, the timing time is 100ms)

R notes mice

Servlet usage

Embedded development: tips and techniques -- the best practice of defensive programming with C

C language: realize the exchange of two numbers without creating temporary variables

pl/sql之各参数详解(“箱子模型“)
随机推荐
Data rich Computing: m.2 meets AI at the edge
Prefix-Tuning: Optimizing Continuous Prompts for Generation
Crowdfunding platform system based on JSP & Servlet
A 404 page source code imitating win10 blue screen
Ch340 RTS DTR pin programming drives OLED
Cookies and session
离职前一定要做好这7件事情,少一件都很麻烦。
常用的接口测试工具
Greed - 55. Jumping game
Convert py file to exe executable file
Summary and interpretation of CONDA virtual environment
Dynamic programming - 474. One and zero
Difference between on, where and having
Notes on writing questions in sword finger offer
搬家通知!
简单、好用的性能测试工具推荐
7/27(板子)染色法判定二分图+求组合数(递推公式)
Appnium--APP自动化测试工具
C语言:不创建临时变量实现两数交换
.net upload files through boundary