当前位置:网站首页>Go language learning: go language journey (III)
Go language learning: go language journey (III)
2022-07-22 18:48:00 【alenliu0621】
List of articles
- Pointers( The pointer )
- Structs( Structure )
- Struct Fields( Fields in the structure )
- Pointers to structs( A pointer to a structure )
- Struct Literals( The literal value of the structure )
- Arrays( Array )
- Slices( section )
- Slices are like references to arrays( Slices are like references to arrays )
- Slice literals( Slice literal )
- Slice defaults( Default value of slice index )
- Slice length and capacity( Slice length and capacity )
- Nil slices( Empty section )
- Creating a slice with make( Use make Create a slice )
- Slices of slices( Slice of slice )
- Appending to a slice( Append element to slice )
- Range
- Maps( Dictionary or mapping )
- Map literals( Dictionary literal value )
- Mutating Maps( Operation Dictionary )
- Function values( Function value )
- Function closures( A function closure )
Pointers( The pointer )
Go Language has pointers . A pointer holds 【 save 】 Address with a value .
*T
It's a point T
Pointer type of type value . Its zero value is nil
.
var p *int
&
The operator generates a pointer to its operand .
i := 42
p = &i
*
Operator is used to get the value pointed to by the pointer .
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is also called an indirect reference .
Unlike C Language ,Go There is no pointer operation .
Sample code :
package main
import "fmt"
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
Output :
42
21
73
Structs( Structure )
A structure is a collection of domains .
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{
1, 2})
}
Output :
{1 2}
Struct Fields( Fields in the structure )
The field of the structure uses a dot .
visit .
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{
1, 2}
v.X = 4
fmt.Println(v.X)
}
Output :
4
Pointers to structs( A pointer to a structure )
The fields in the structure can be accessed through the structure pointer .
When we have a structure pointer p
when , To access X
Domain , We can write (*p).x
. However , This writing method is very bloated , therefore Go Language allows us to write directly p.x
, There is no need to explicitly indirectly reference .
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{
1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
}
Output :
{1000000000 2}
Struct Literals( The literal value of the structure )
A structure literal 【 By listing the values of the fields it contains 】 Represents a newly assigned structure value .
You can use Name:
The syntax only lists some fields . The order of named domains is irrelevant .
special &
The operator returns a pointer to the structure value .
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{
1, 2} // has type Vertex
v2 = Vertex{
X: 1} // Y:0 is implicit
v3 = Vertex{
} // X:0 and Y:0
p = &Vertex{
1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
}
Output :
{1 2} &{1 2} {1 0} {0 0}
Arrays( Array )
[n]T
Is a containing n individual T
Array type of type value .
expression
var a [10]int
Variable declared a Is a containing 10 Array of integers .
The length of an array is part of its type , So the size of the array cannot be changed .
package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
primes := [6]int{
2, 3, 5, 7, 11, 13}
fmt.Println(primes)
}
Output :
Hello World
[Hello World]
[2 3 5 7 11 13]
Slices( section )
An array has a fixed size . A slice , On the other hand , Is a dynamic size , An array that provides a flexible view of array elements . In practice, , Slicing is more common than arrays .
[]T
Is an element of type T
Slice type for .
An index of a slice separated by two colons 【 A lower bound , An upper bound 】 formation :
a[low:high]
This is a half open interval , Including the first element , But it doesn't include the last element .
The following expression
a[1:4]
Create array a A slice of , It includes arrays a Of the 2 One to the first 4 Elements 【 The array element index is from 0 Start 】.
package main
import "fmt"
func main() {
primes := [6]int{
2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s)
}
Output :
[3 5 7]
Slices are like references to arrays( Slices are like references to arrays )
A slice does not store any data , It only describes a selection interval of the underlying array .
Modifying the elements in the slice is to modify the elements of the underlying array . All slices with the same underlying array will see these changes .
package main
import "fmt"
func main() {
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
}
Output :
[John Paul George Ringo]
[John Paul] [Paul George]
[John XXX] [XXX George]
[John XXX George Ringo]
Slice literals( Slice literal )
A slice literal is an array literal without length .
This is an array literal :
[3]bool{
true, true, false}
The following slice literal will also create an array as above , Then build a slice that references it :
[]bool{
true, true, false}
Sample code :
package main
import "fmt"
func main() {
q := []int{
2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{
true, false, true, true, false, true}
fmt.Println(r)
s := []struct {
i int
b bool
}{
{
2, true},
{
3, false},
{
5, true},
{
7, true},
{
11, false},
{
13, true},
}
fmt.Println(s)
}
Output :
[2 3 5 7 11 13]
[true false true true false true]
[{2 true} {3 false} {5 true} {7 true} {11 false} {13 true}]
Slice defaults( Default value of slice index )
When using slices , You can ignore the lower bound index or the upper bound index and use their default values .
The default value of the lower bound index is 0, The default value of the upper bound index is the length of the underlying array .
For arrays
var a [10]int
Come on , These slice expressions are the same :
a[0:10]
a[:10]
a[0:]
a[:]
Sample code :
package main
import "fmt"
func main() {
s := []int{
2, 3, 5, 7, 11, 13}
s = s[1:4]
fmt.Println(s)
s = s[:2]
fmt.Println(s)
s = s[1:]
fmt.Println(s)
}
Output :
[3 5 7]
[3 5]
[5]
Slice length and capacity( Slice length and capacity )
A slice has two attributes: length and capacity .
The length of the slice is the number of elements it contains .
The capacity of slices is contained in the underlying array Calculate from the first element in the slice Number of elements of .
section s The length and capacity of can be used len(s)
and cap(s)
Expression to get .
You can slice the slice again to expand its length , The premise is that its capacity is sufficient .
package main
import "fmt"
func main() {
s := []int{
2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
Output :
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
Nil slices( Empty section )
The zero value of the slice is nil
.
The length and capacity of an empty slice are 0, It has no underlying array .
package main
import "fmt"
func main() {
var s []int
fmt.Println(s, len(s), cap(s))
if s == nil {
fmt.Println("nil!")
}
}
Output :
[] 0 0
nil!
Creating a slice with make( Use make Create a slice )
Slicing can use built-in functions make
establish , This is how to create a dynamically sized array .
make
Function to allocate an array that has been cleared , And return a slice that references this array :
a := make([]int, 5) // len(a)=5
To specify the capacity of the slice , Pass in the third parameter :
b := make([]int, 0, 5) // len(b)=0, cap(b)=5
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:] // len(b)=4, cap(b)=4
Sample code :
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
Output :
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]
Slices of slices( Slice of slice )
Slices can contain any type , Including other slices .
package main
import (
"fmt"
"strings"
)
func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{
"_", "_", "_"},
[]string{
"_", "_", "_"},
[]string{
"_", "_", "_"},
}
// The players take turns.
board[0][0] = "X"
board[2][2] = "O"
board[1][2] = "X"
board[1][0] = "O"
board[0][2] = "X"
for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
Output :
X _ X
O _ X
_ _ O
Appending to a slice( Append element to slice )
Adding new elements to slices is common , therefore Go A built-in function is provided append
.builtin Package document It describes append
function :
func append(s []T, vs ...T) []T
The first parameter s Is a type of T
The section of , The remaining parameters are to be appended to the slice of type T
Value .
append
The returned value is a slice containing all the elements of the original slice plus the additional new elements .
If the underlying array s The capacity of is too small to accommodate the new value , Then a larger array will be allocated . The returned slice will point to the newly allocated array .
Range
for
Cyclic range
Form iteration a slice or dictionary .
When iterating over a slice , Each iteration returns two values . The first is the index , The second is a copy of the element on this index .
package main
import "fmt"
var pow = []int{
1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
Output :
2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128
You can use _
To ignore indexes or values :
for i, _ := range pow
for _, value := range pow
If you set items to index , Then you can ignore the second variable :
for i := range pow
Sample code :
package main
import "fmt"
func main() {
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
Output :
1
2
4
8
16
32
64
128
256
512
Maps( Dictionary or mapping )
A dictionary will key words 【key】 Mapping to value .
The zero value of the dictionary is nil
. One nil
There is no dictionary key, And there's nothing key Can be added .
make
Function returns a dictionary of the specified type , This dictionary has been initialized , You can use it directly .
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func main() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m["Bell Labs"])
}
Output :
{40.68433 -74.39967}
Map literals( Dictionary literal value )
Dictionary literals are similar to struct literals , however key It's necessary .
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
func main() {
fmt.Println(m)
}
Output :
map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]
If the top-level type is just a type name , Then it can be omitted from the literal element .
for example
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
It can be written directly as
var m = map[string]Vertex{
"Bell Labs": {
40.68433, -74.39967},
"Google": {
37.42202, -122.08408},
}
Mutating Maps( Operation Dictionary )
Insert or update an element in the dictionary :
m[key] = elem
Get an element :
elem = m[key]
Delete an element :
delete(m, key)
Use binary (two-value ) Assign a value to test a key Whether there is :
elem, ok = m[key]
If key stay m in ,ok yes true
, It is false
.
If key be not in m in , that elem The value of is the zero value of the dictionary element .
Be careful : If elem perhaps ok Not yet declared , Then you can use a short declaration form :
elem, ok := m[key]
Sample code :
package main
import "fmt"
func main() {
m := make(map[string]int)
m["Answer"] = 42
fmt.Println("The value:", m["Answer"])
m["Answer"] = 48
fmt.Println("The value:", m["Answer"])
delete(m, "Answer")
fmt.Println("The value:", m["Answer"])
v, ok := m["Answer"]
fmt.Println("The value:", v, "Present?", ok)
}
Output :
The value: 42
The value: 48
The value: 0
The value: 0 Present? false
Function values( Function value )
Functions are also values . They can be used as function parameters and return values like other values .
package main
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow))
}
Output :
13
5
81
Function closures( A function closure )
Go Functions can be closures . A closure is a function value that refers to an external variable of a function in the function body . Function can access and modify referenced variables . In this case , Functions are bound to variables .
for example ,adder Function returns a closure . Each closure is bound with a sum Variable :
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
Output :
0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90
边栏推荐
- [SDIO] sd2.0 protocol analysis summary (II) -- SD card identification & data transmission process
- [Nordic] nrf52810 OTA upgrade (III) – DFU theoretical analysis
- Go 语言学习:Go 语言之旅——练习题及参考答案
- LeetCode: 620. 有趣的电影
- 1.qt 查看源码
- amh多mysql版本共存?
- win10sp1升到最新版本;QT5.9.6静态编译(network有效)
- PAT基础习题集7-26 单词长度(精简代码)
- Summary 20220120
- [STM32] STM32 SDIO SD card read / write test (IV) -- SD_ Transfer mode phase of test
猜你喜欢
LeetCode: 185. 部门工资前三高的所有员工
C language simple TCP server program
LeetCode: 184. 部门工资最高的员工
App mobile End test [6] application (APK) package Management and Activity
IP, subnet mask, gateway, IPS and IDS
PTA 基础题7-28猴子选大王(简单方法)
数据湖简单记录
【SDIO】SD2.0协议分析总结(一)-- SD卡基本概率介绍
06.里氏替换原则(Liskov Substitution Principle,LSP)
[STM32] STM32 SDIO SD card read / write test (III) -- SD_ Init card stage of init
随机推荐
Summary 20220121
Fortress machine, DMZ area
App移动端测试【6】应用程序(apk)包管理与activity
总结20220211
Simple demonstration and prevention of CSRF attack in PHP development
LeetCode 720. 词典中最长的单词
Interview experience of Android Internet manufacturers
LeetCode: 596. 超过5名学生的课
1.针对QDate()的日期指向那边, 2.QT_VERSION的用法总结
[SDIO] SDIO, SD card, FatFs file system related article index
总结20220214
[STM32] STM32 SDIO SD card read / write test (II) -- SD_ Power on phase of init
QT的sprintf重写;qt下内容按界面的缩放而缩放(不改变字体大小)
总结20220118(二叉树)
PAT乙级1020月饼(注意测点)
Go memory model
LeetCode 653. 两数之和 IV - 输入 BST
【SDIO】SDIO、SD卡、FatFs文件系统相关文章索引
Summary 20220213 (Floyd and Dijkstra)
LeetCode: 185. 部门工资前三高的所有员工