当前位置:网站首页>go struct
go struct
2022-04-23 20:39:00 【baboon_ chen】
One 、go sturct type
1、 Value type
2、struct The name cannot match the package name
3、 Both structure pointer and structure variable can pass through .
Visiting members , This is a kind of grammar sugar .
4、struct Initialization example
type Point struct {
X int
Y int
}
func test1() {
// (1) Declare variables first , Then assign a value to the member
var p1 Point
p1.X = 10
p1.Y = 5
// (2) Direct initialization
p2 := Point{
X: 10, // It is allowed to initialize only some members
}
// (3) Initialize pointer type
var p3 *Point = &Point{
}
// (4) Initialize pointer type , And the assignment
p4 := &Point{
X: 10,
Y: 5,
}
// (5) Use new Construct pointer
var p5 *Point = new(Point)
p5.X = 10
p5.Y = 5
}
Two 、go Memory layout
1、 Take up a continuous memory space
func test2() {
type Array struct {
A, B, C, D int
}
arr := Array{
A: 1, B: 2, C: 3, D: 4,
}
fmt.Printf("the address of A:%p\n", &arr.A)
fmt.Printf("the address of B:%p\n", &arr.B)
fmt.Printf("the address of C:%p\n", &arr.C)
fmt.Printf("the address of D:%p\n", &arr.D)
}
/* the address of A:0xc00011c120 the address of B:0xc00011c128 the address of C:0xc00011c130 the address of D:0xc00011c138 */
2、 There is no constructor , If necessary, you need to realize
func creatPoint(x, y int) Point {
return Point{
X: x,
Y: y,
}
}
func test3() {
fmt.Printf("the new Point is %#v\n", creatPoint(1, 2))
}
3、 ... and 、 Anonymous field
Anonymous fields are just types , No member name ,go Will default the type to the field name .
1、 How anonymous fields are accessed
type User struct {
name string
age int
float32
}
func test4() {
var li User
li.float32 = 9.9
fmt.Printf("the value of li:%#v\n", li)
}
2、 Anonymous structures can be nested in structures , Priority of field search in structure : From top to bottom , Give priority to the members in the structure , Then look for the fields in the anonymous structure .
type Address struct {
Location string
CreatTime string
}
type User struct {
Name string
Age int
CreatTime string
Address
}
func test5() {
var li User
li.CreatTime = "2020"
fmt.Printf("the value of li:%#v\n", li)
}
/* the value of li:main.User{Name:"", Age:0, CreatTime:"2020", Address:main.Address{Location:"", CreatTime:""}} */
3、 How to resolve naming conflicts : If more than one anonymous struct member contains a field with the same name , During the interview , You must specify which field in the anonymous structure to access , Otherwise, it will compile and report errors . The solution to the conflict is by specifying the type of anonymous structure .
type Address struct {
Location string
CreatTime string
}
type Email struct {
Value string
CreatTime string
}
type User struct {
Name string
Age int
Address
Email
}
func test6() {
var li User
li.Email.CreatTime = "2020"
//li.CreatTime = "2020" //Error:ambiguous selector li.CreatTime
fmt.Printf("the value of li:%#v\n", li)
}
/* the value of li:main.User{Name:"", Age:0, Address:main.Address{Location:"", CreatTime:""}, Email:main.Email{Value:"", CreatTime:"2020"}} */
Four 、 Access right
Member names begin with uppercase to indicate public , Xiao Yu said private .
5、 ... and 、 Structure tag
tag Is the meta information of the structure , It can be in transit ⾏ It's read by reflection mechanism . After field type ⾯, Enclosed in back quotes
key-value
String of structure , Multipletag
Expand with commas .
type User struct {
Name string `json:"value Name"`
Age int
Address
Email
}
6、 ... and 、 Object oriented definition method
1、 Set the receiver of a method before declaring the function ( Type of structure , It can also be a pointer type ), When a method is called, it is passed to the receiver of a method ( Better pass the pointer , Avoid value passing )
2、 You can add methods to any type .
type Integer int
func (i Integer) print() {
fmt.Println(i)
}
func test7() {
var a Integer = 10
a.print()
}
3、go Use in Combine
The way to achieve inheritance .
type Animal struct {
name string
age int
}
func (this *Animal) talk() {
fmt.Printf("I am %v\n", this.name)
}
type Dog struct {
family string
*Animal
}
func (this *Dog) run() {
fmt.Printf("my faimly is %v\n", this.family)
}
func test8() {
d := &Dog{
family: "Hong",
Animal: &Animal{
name: "xiaohei",
age: 10,
},
}
d.talk()
d.run()
}
7、 ... and 、 Structure serialization and deserialization
Example :
func test9() {
p1 := &Point{
X: 10,
Y: 5,
}
pJson, err := json.Marshal(p1)
if err == nil {
fmt.Printf("Serialization: %v\n", string(pJson))
}
var s string = `{"X":10,"Y":5}`
var p2 *Point = &Point{
}
err = json.Unmarshal([]byte(s), p2)
if err == nil {
fmt.Printf("the value of p2:%#v\n", p2)
}
}
8、 ... and 、 Anonymous structure initialization
Example :
func test10() {
type cat struct {
Name string
Color string
Age int
Home struct {
Adderess string
PostCode int
}
}
ins := cat{
Name: "Tom",
Color: "Dark",
Age: 5,
Home: struct{
Adderess string
PostCode int
}{
"England",
1024,
},
}
}
版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351278.html
边栏推荐
- GO語言開發天天生鮮項目第三天 案例-新聞發布系統二
- Numpy - creation of data type and array
- LeetCode 116. 填充每个节点的下一个右侧节点指针
- Solution: NPM err! code ELIFECYCLE npm ERR! errno 1
- Leetcode 74. Search two-dimensional matrix
- Automatically fill in body temperature and win10 task plan
- 一. js的深拷贝和浅拷贝
- Analysis of the relationship between generalized Bim and CAD under the current background
- [stack and queue topics] - sliding window
- 2021-06-29 C escape character cancellation and use
猜你喜欢
Resolve the eslint warning -- ignore the warning that there is no space between the method name and ()
Devaxpress report replay: complete the drawing of conventional two-dimensional report + histogram + pie chart
Some basic configurations in interlij idea
Operation of numpy array
Cmake project under vs2019: calculating binocular parallax using elas method
On BIM data redundancy theory
Vscode download speed up
ArcGIS JS version military landmark drawing (dovetail arrow, pincer arrow, assembly area) fan and other custom graphics
The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
How can matlab obtain the truncated image in trainingimagelabeler
随机推荐
The problem of 1 pixel border on the mobile terminal
[PTA] l2-011 play with binary tree
Some basic knowledge of devexpress report development
Recommend an open source free drawing software draw IO exportable vector graph
BMP JPEG picture to vector image contourtrace
LeetCode 1351、统计有序矩阵中的负数
上海回應“面粉官網是非法網站”:疏於運維被“黑”,警方已立案
High paid programmer & interview question series 91 limit 20000 loading is very slow. How to solve it? How to locate slow SQL?
Customize timeline component styles
SQL gets the latest record of the data table
堡垒机、跳板机JumpServer的搭建,以及使用,图文详细
Latest investigation and progress of building intelligence based on sati
Mathematical modeling column | Part 5: MATLAB optimization model solving method (Part I): Standard Model
Common form verification
2021-09-02 unity project uses rider to build hot change project failure record of ilruntime
Psychological formula for converting RGB to gray value
RT-1052学习笔记 - GPIO架构分析
Cmake project under vs2019: calculating binocular parallax using elas method
Matlab: psychtoolbox installation
Come in and teach you how to solve the problem of port occupation