当前位置:网站首页>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-valueString of structure , MultipletagExpand 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
边栏推荐
- Numpy Index & slice & iteration
- 上海回應“面粉官網是非法網站”:疏於運維被“黑”,警方已立案
- Installation and use of NVM
- Come in and teach you how to solve the problem of port occupation
- Recognition of high-speed road signs by Matlab using alexnet
- Leetcode 1337. Row K with the weakest combat effectiveness in the matrix
- XXXI` Prototype ` displays prototype properties and`__ proto__` Implicit prototype properties
- 【栈和队列专题】—— 滑动窗口
- 【PTA】L1-006 连续因子
- Operation of numpy array
猜你喜欢

Some basic knowledge of devexpress report development

Automatically fill in body temperature and win10 task plan

Devaxpress report replay: complete the drawing of conventional two-dimensional report + histogram + pie chart

高薪程序员&面试题精讲系列91之Limit 20000加载很慢怎么解决?如何定位慢SQL?

vulnhub DC:1渗透笔记

Matlab matrix index problem

Recommend an open source free drawing software draw IO exportable vector graph

High paid programmer & interview question series 91 limit 20000 loading is very slow. How to solve it? How to locate slow SQL?

Modeling based on catiav6

LeetCode 74、搜索二维矩阵
随机推荐
Case of the third day of go language development fresh every day project - news release system II
SQL: query duplicate data and delete duplicate data
Shanghai responded that "flour official website is an illegal website": neglect of operation and maintenance has been "hacked", and the police have filed a case
一. js的深拷贝和浅拷贝
The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
Es error: request contains unrecognized parameter [ignore_throttled]
LeetCode 1337、矩阵中战斗力最弱的 K 行
Learn to C language fourth day
Unity animation creates sequence frame code and generates animationclip
How can matlab obtain the truncated image in trainingimagelabeler
6-5 string - 2 String copy (assignment) (10 points) the C language standard function library includes the strcpy function for string copy (assignment). As an exercise, we write a function with the sam
Leetcode 1337. Row K with the weakest combat effectiveness in the matrix
Customize timeline component styles
Async function ------ ES6
Vscode download speed up
Leetcode 1351. Negative numbers in statistical ordered matrices
Go限制深度遍历目录下文件
Recognition of high-speed road signs by Matlab using alexnet
[graph theory brush question-4] force deduction 778 Swimming in a rising pool
Vulnhub DC: 1 penetration notes