当前位置:网站首页>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
边栏推荐
- Scrapy教程 - (2)寫一個簡單爬蟲
- Bash script learning -- for loop traversal
- 【SQL】字符串系列2:将一个字符串根据特定字符分拆成多行
- The ODB model calculates the data and outputs it to excel
- Latest investigation and progress of building intelligence based on sati
- MySQL 存储过程和函数
- Identifier CV is not defined in opencv4_ CAP_ PROP_ FPS; CV_ CAP_ PROP_ FRAME_ COUNT; CV_ CAP_ PROP_ POS_ Frames problem
- "Meta function" of tidb 6.0: what is placement rules in SQL?
- 打新债中签以后怎么办,网上开户安全吗
- 2022DASCTF Apr X FATE 防疫挑战赛 CRYPTO easy_real
猜你喜欢
High paid programmer & interview question series 91 limit 20000 loading is very slow. How to solve it? How to locate slow SQL?
The ODB model calculates the data and outputs it to excel
上海回應“面粉官網是非法網站”:疏於運維被“黑”,警方已立案
Three. Based on ply format point cloud voxel model JS upload interface writing
vulnhub DC:1渗透笔记
The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
Numpy Index & slice & iteration
JS arrow function user and processing method of converting arrow function into ordinary function
Rt-1052 learning notes - GPIO architecture analysis
DOS command of Intranet penetration
随机推荐
Unity ECS dots notes
PostgreSQL basic functions
Experience of mathematical modeling in 18 year research competition
[PTA] l1-006 continuity factor
How to configure SSH public key in code cloud
【SQL】字符串系列2:将一个字符串根据特定字符分拆成多行
Install MySQL 5.0 under Linux 64bit 6 - the root password cannot be modified
Go language development Daily Fresh Project Day 3 Case - Press Release System II
Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
bounding box iou
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
Development of Matlab GUI bridge auxiliary Designer (functional introduction)
Unity solves Z-fighting
黑客的入侵方式你知道几种?
Solution to PowerDesigner's failure to connect to MySQL in x64 system
Numpy mathematical function & logical function
Scrapy教程 - (2)寫一個簡單爬蟲
LeetCode 542、01 矩阵
Elastic box model
LeetCode 709、转换成小写字母