当前位置:网站首页>An introductory example of structure and combinatorial ideas in go language
An introductory example of structure and combinatorial ideas in go language
2022-07-24 02:50:00 【march of Time】
Reference resources 《go Language from introduction to advanced practice 》 And Han Shunping 《go Language core programming 》
About go Object orientation in
- Golang It also supports object-oriented programming (OOP), But it's different from traditional object-oriented programming , It's not a pure object-oriented language . So we say Golang It is more accurate to support object-oriented programming features .
- Golang There is no class (class),Go The structure of language (struct) And other programming languages (class) Have equal status , You can understand Golang Is based on struct To achieve OOP Characteristic .
- Golang Object oriented programming is very concise , Get rid of the tradition OOP Inheritance of language 、 Method overloading 、 Constructors and destructors 、 Hidden this Pointer, etc
- Golang There is still inheritance from object-oriented programming , Encapsulation and polymorphism , Just the way of implementation and others OOP The language is different , Like inheritance :Golang No, extends keyword , Inheritance is achieved through anonymous fields .
- Golang object-oriented (OOP) Very elegant ,OOP Itself is the language type system (type system) Part of , Through interface (interface) relation , Low coupling , It's also very flexible .
go A structure in :
type Structure name struct {
field1 type
field2 type
}
Pay attention here :
If the field type of the structure is : The pointer ,slice, and map All zero values of are nil, That is, there is no space allocated / If you need to use a field like this , It needs to be done first make, Can be used .
for example :
type Person struct{
Name string
Age int
Scores [5]float64
ptr *int/ The pointer
slice []int// section
map1 map[string]string //map
}
Create examples :
var p1 Person
p1.slice = make([]int,10)
p1.slice[10]=100
p1.map1 = make(map[string]string)
p1.map1["k1"]="acb"
The fields of different structure variables are independent , They don't influence each other , Change of a structure variable field , Does not affect the other , A structure is a value type , Example :
var monster1 Monster
monster1.Name=" But the king bull "
monster1.Age= 500
monster2:=monster1// A structure is a value type , The default value is copy monster2.Name=" Qingniujing "
fmt.Print1n("monster:1=",monster1)//monster1={ But the king bull 500]
fmt.Println(monster2=",monster2)//monster2={ Qingniujing 500}
Create structure variables and access structure fields
Yes 4 The way :
1. The way 1- Make a direct statement
Case presentation : var person Person
2. The way 2-{}
Case presentation : var person Person = Person{}
3. The way 3-&
Case study : var person *Person = new (Person)
4. The way 4-{}
Case study : var person *Person = &Person{}
It is also a pointer type , The assignment method is the same as 3
explain :
- The first 3 Species and 4 One way to return is the structure pointer .
- The standard way for structure pointers to access fields should be :(* Structure pointer ). Field name , such as (*person).Name = “tom”
- but go Made a simplification , Structure pointers are also supported . Field name , such as person.Name = “tom”. More in line with the habits of programmers ,go Compiler bottom pair person.Name Made a transformation (*person).Name.
There is one of the simplest ways , Don't declare var, Directly a variable name ,go Will automatically identify the type :
abc := new (Person)
struct Type of memory allocation mechanism

The output is zero : p2.Name = tom p1.Name = Xiao Ming
Memory allocation diagram :
For the following code :
Output :、
Memory allocation :
Be careful :
- All fields of the structure are contiguous in memory
- Structs are user-defined types , When converting with other types, you need exactly the same fields ( name 、 Number and type )

3)3) The structure is type Redefinition ( Equivalent to taking an alias ),Golang Think of it as a new data type , But they can turn strongly 
4) struct On each field of , You can write a tag, The tag You can get it through the reflection mechanism , Common usage scenarios are serialization and deserialization .
give an example :
//1. Create a Monster Variable
monster:=Monster{
" But the king bull ",500," Banana fan ~"}
//2. take monster The variable is serialized to json Format string
//json.Marshal Use reflection in function ,
jsonstr,err= json.Marshal(monster)
if err !=nil
fmt.Println("json Handling errors ",err)
fmt.Println("jsonstr",string(jsonstr))
Use the combination idea to describe the characteristics of objects
In object-oriented thinking , Implementing object relationships requires “ Inherit ” characteristic . for example , Humans cannot fly , Birds can fly . Both humans and birds can inherit from viable walkers , But only birds inherit from flying . Object-oriented design principles also suggest that objects should not use multiple inheritance , Some object-oriented languages prohibit multiple inheritance at the language level , Such as C# and Java Language . Birds inherit from both walkers and fliers , This is obviously problematic . In object-oriented thinking, we should correctly realize the multiple characteristics of objects , Only some delicate design can be used to remedy it . Go The embedded feature of language structure is a kind of combinatorial feature , Using composite properties, you can quickly build different properties of objects .
Example : The characteristics of people and birds
// Flightable
type Flying struct{
}
func (f *Flying) Fly() {
fmt.Println("can fly")
}
// Walkable
type Walkable struct{
}
func (f *Walkable) Walk() {
fmt.Println("can calk")
}
// human beings
type Human struct {
Walkable // Human beings can walk
}
// birds
type Bird struct {
Walkable // Birds can walk
Flying // Birds can fly
}
func main() {
// Instantiate birds
b := new(Bird)
fmt.Println("Bird: ")
b.Fly()
b.Walk()
// Instantiate human
h := new(Human)
fmt.Println("Human: ")
h.Walk()
}

Initialize the structure embedded
When the structure is initialized , Initialize the type embedded in the structure as a field name, just like an ordinary structure , Detailed implementation process :
package main
import "fmt"
// wheel
type Wheel struct {
Size int
}
// engine
type Engine struct {
Power int // power
Type string // type
}
// vehicle
type Car struct {
Wheel
Engine
}
func main() {
c := Car{
// Initialize wheel
Wheel: Wheel{
Size: 18,
},
// Initialize engine
Engine: Engine{
Type: "1.4T",
Power: 143,
},
}
fmt.Printf("%+v\n", c)
}
Output :
{Wheel:{Size:18} Engine:{Power:143 Type:1.4T}}
Initialize anonymous structure :
Sometimes consider the convenience of writing code , The structure will be defined directly in the embedded structure . in other words , The definition of a structure is not externally referenced to . When initializing the embedded structure , You need to declare the structure again to give the data .
package main
import "fmt"
// wheel
type Wheel struct {
Size int
}
// vehicle
type Car struct {
Wheel
// engine
Engine struct {
Power int // power
Type string // type
}
}
func main() {
c := Car{
// Initialize wheel
Wheel: Wheel{
Size: 18,
},
// Initialize engine
Engine: struct {
Power int
Type string
}{
Type: "1.4T",
Power: 143,
},
}
fmt.Printf("%+v\n", c)
}
Member names conflict
The embedded structure may have the same member name , What happens when members have duplicate names ? Here is an example to explain .
01 package main
02
03 import (
04 "fmt"
05 )
06
07 type A struct {
08 a int
09 }
10
11 type B struct {
12 a int
13 }
14
15 type C struct {
16 A
17 B
18 }
19
20 func main() {
21 c := &C{
}
22 c.A.a = 1
23 fmt.Println(c)
24 }
The code description is as follows : · The first 7 Xing He 11 Row defines two ownership a int The structure of the field . · The first 15 The structure of the row is embedded A and B The structure of the body . · The first 21 Line instantiation C Structure . · The first 22 OK, in the usual way , Access the embedded structure A Medium a Field , And the assignment 1. · The first 23 Rows can be output and instantiated normally C Structure . next , Will be the first 22 Change the line to the following code :
func main() {
c := &C{
}
c.a = 1
fmt.Println(c)
}
Then compile and run , Compiler error : Compiler notification C Selector a Cause ambiguity , in other words , The compiler cannot decide to 1 Assign to C Medium A still B Fields in a.
边栏推荐
- Tutoriel sur l'utilisation de la ligne de temps unitaire
- Relational expression greater than > less than < congruence = = = Nan isnan() logical operator double sense exclamation point!! & |% +-- Short circuit calculation assignment expression shortcut operat
- Some consulting questions and answers raised by friends who lack programming foundation and want to change careers in ABAP development post
- How to get gait energy map Gei
- go strconv
- UIE: 信息抽取的大一统模型
- Ugui source code analysis - imaterialmodifier
- 相关性(correlation)
- Symbol type
- Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire
猜你喜欢

动态规划-01背包问题

Attack and defense world web practice area (backup, cookie, disabled_button)
[email protected]使用原理"/>(六)装饰器扩展之[email protected]使用原理

Composition API (in setup) watch usage details
![[management / upgrade] * 02. View the upgrade path * FortiGate firewall](/img/c7/da6db46d372e7462cd14852b662d6d.png)
[management / upgrade] * 02. View the upgrade path * FortiGate firewall

ssm的求职招聘系统兼职应聘求职

22 -- 二叉搜索树的范围和

Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire

The process of solving a bug at work

Jina AI and datawhale jointly launched a learning project!
随机推荐
Correlation
Doodle icons - a free commercial graffiti style icon library, cute, light and unique
go errors
508. 出现次数最多的子树元素和-哈希表法纯c实现
Ugui source code analysis - imaskable
PMP first-hand data and information acquisition
理解加载class到JVM的时机
Nodejs builds cloud native microservice applications based on dapr, a quick start guide from 0 to 1
JpaRepository扩展接口
Understand the low code implementation of microservices
Nodejs builds cloud native microservice applications based on dapr, a quick start guide from 0 to 1
JS when transferring parameters, the incoming string has data; No data when number is passed in; 2[0] is right! Number type data can be subscripted
Mysql database, sorting and single line processing functions
Take you into the world of MySQL mvcc
Job hunting and recruitment system of SSM part-time job hunting
redis数据类型概念
Composition API (in setup) watch usage details
Attack and defense world web practice area (backup, cookie, disabled_button)
C language exercises
SkyWalking分布式系统应用程序性能监控工具-上