当前位置:网站首页>Structure of golang
Structure of golang
2022-07-03 07:40:00 【m0_ fifty-two million three hundred and thirty-nine thousand fi】
GoLang Structure
List of articles
Basic use
First , Give some understanding of the structure .
A structure is a collection of attributes , These attributes can be called fields , It's actually some variables in the program . Through these properties ( Field ) To describe the characteristics of something . actually , Structure is the abstraction of the substance to be described .
1. Defining structure
type struct_name struct{
var_name1 type
var_name2 type
var_name3 type
.
.
.
var_namen type
}
2. Declare and initialize the structure object
Examples of structures :
type Animal struct{
name string
age int
sex boolean
}
- Method 1 : Declare struct variables , And then through
.Operator access assignment , To initialize
var st1 Animal
st1.name = " cat "
st1.age = 3
st1. sex = false
println(st1.name)
println(st1.age)
println(st1.sex)
// The result is :
// cat
//3
//false
- Method 2 : Declaration is used in conjunction with
{}To initialize
var st1 Animal = Animal{
name: " cat ",
age: 3,
sex: false, // The last comma here cannot be omitted , If you want to omit , Then the right brace should be on this line
}
// Or abbreviated as the following form
st2 := Animal{
name: " cat ",
age: 3,
sex: false,
}
// Or abbreviated as the following form
st3 := Animal{
// When using this form , The assignment order is consistent with the declaration order of variables in the structure .
" cat ",
3,
false,
}
- Method 3 : Use
new()function : A function designed to create a pointer of a certain type
st4 := new(Animal)
st4.name = " cat "
st4.age = 3
st4.sex = false
fmt.Printf("%p---%T", st4, st4)
// The result is :
//0xc0000593c0---*main.Person
From the return result *main.Person It can be seen that , Use new() Example of structure created by function , The return is a structure pointer , It points to the use new() Function opens up space .
meanwhile , For structure pointers , Can pass . Operator directly accesses the field it points to the structure .
3. Value type and reference data type
Golang In language :
Value type :int, float, bool, string, array, struct etc.
Reference type : slice, map ,function, pointer etc.
- Aim at
struct, Its example is value type . When assigning a structural variable to another structural variable , A copy will occur . such as :st1 := st2, herest2It has been initialized in advance , It will best2Copy the value of , Then putst1In memory space .
Example :
var st2 Animal = Animal{
name: " cat ",
age: 3,
sex: false,
}
st1 := st2
st1.name = " Dog "
fmt.Println(st1)
fmt.Println(st2)
// The result is :
//{ Dog 3 false}
//{ cat 3 false}
As can be seen from the above code , modify st1 It doesn't affect st2 Value .
Example :
var st2 *Animal = new(Animal)
st2.name = " cat "
st2.age = 3
st2.sex =false
st1 := st2
st1.name = " Dog "
fmt.Println(st1)
fmt.Println(st2)
// The result is :
//&{ Dog 3 false}
//&{ Dog 3 false}
//0xc0000503c0---0xc0000503c0
so ,st1 and st2 Are all references to structures , All point to the same memory space . So pass st1 or st2 Modify the fields of the structure , Will affect the value of the other party .
Anonymous structure and anonymous field
- Anonymous structure
When we need to use a structure and declare its variables, there are two ways . One is to define the structure first , Then declare its variables ; The other is to use anonymous structures . Use anonymous structures , No need to use type Keyword specifies the name of the structure type .
Use the syntax :
struct{
field1 type
filed2 type
.
.
.
filedn type
}{
field1: value1,
field2: value2,
field3: valur3,
.
.
.
fieldn: valuen,
}
analysis : The content in the first brace , It is the field definition of anonymous structure . The content in the second brace is the initialization of anonymous structure fields
Examples of use :
animal := struct{
name string
age int
}{
name: " cat ",
age: 3,
}
fmt.Println(animal)
// The result is :
{
cat 3}
- Anonymous structure field
For fields in the structure , Sometimes its field name can be omitted . notes : Variables in the structure can also be called fields .
Example :
type Animal struct{ string int }Make a statement
AnimalThe structural variable of :var a Animal = Animal{ " cat ", 3}How to access the fields of a structure without field names ? In this case , The type of the field is treated as the field name by default . in other words , The type of field plays the role of data type , It also acts as a field name .
Example :
var a Animal = Animal{ " cat ", 3} fmt.Println(a.string, a.int) // The result is : // cat 3
- According to the above , You can know , The anonymous field of the structure can only be used when the field type of the current structure is not complex . That is, when multiple fields of the same type appear in the structure , Anonymous fields cannot be used . Because the type of anonymous field acts as a field identifier , If anonymous fields of the same type appear , Then it is impossible to determine which field to access .
Example : The following code snippet , Will make the compiler report errors
type Animal struct{ string int string // Here are two string Anonymous field of type , Report errors }
Nesting of structures
Simply speaking , There is another definition of structure in the definition of structure , This is the nesting of structures .
When to use it ? commonly , When one structure has another structure in its attributes, nesting of structures will be used .
as follows :
type Book struct{
// Definition Book Structure , The name and price of the description book
name string
price float64
}
type Student struct{
// Definition student Structure , Describe the student's name , Age , And the books I have read
name string
age int
book Book
}
Reference material
- https://www.bilibili.com/video/BV1jJ411c7s3?p=86&vd_source=008445eb63b17edad78a03ae3d20c08a
- https://www.runoob.com/go/go-structures.html
边栏推荐
- Read config configuration file of vertx
- Hnsw introduction and some reference articles in lucene9
- 【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
- 項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
- Go language foundation ------ 12 ------ JSON
- Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
- Leetcode 198: 打家劫舍
- Custom generic structure
- 【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
- Application of pigeon nest principle in Lucene minshouldmatchsumscorer
猜你喜欢

Application of pigeon nest principle in Lucene minshouldmatchsumscorer

Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function

PAT甲级 1027 Colors in Mars

研究显示乳腺癌细胞更容易在患者睡觉时进入血液

项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现

为什么说数据服务化是下一代数据中台的方向?

Inverted chain disk storage in Lucene (pfordelta)

Analysis of the problems of the 12th Blue Bridge Cup single chip microcomputer provincial competition

Use of other streams

Lucene hnsw merge optimization
随机推荐
Hnsw introduction and some reference articles in lucene9
GoLang之结构体
Some experiences of Arduino soft serial port communication
OSPF protocol summary
Go language foundation ----- 18 ----- collaboration security, mutex lock, read-write lock, anonymous lock, sync Once
Hisat2 - stringtie - deseq2 pipeline for bulk RNA seq
技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
Go language foundation ----- 07 ----- method
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
UA camouflage, get and post in requests carry parameters to obtain JSON format content
Sent by mqtt client server of vertx
Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
Vertx multi vertical shared data
Robots protocol
技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer
PgSQL converts string to double type (to_number())
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
Leetcode 198: 打家劫舍