当前位置:网站首页>[golang] quick review guide quickreview (II) -- slice
[golang] quick review guide quickreview (II) -- slice
2022-06-23 20:21:00 【DDGarfield】
In the last article 【Golang】 Quick review guide QuickReview( One )—— character string string String flipping code implementation , Mentioned slicing , Slice in golang Is a very important data type . Speaking of slicing , You have to mention arrays , But the length of the array is fixed and the length of the array is part of the type , So arrays have a lot of limitations . And slice (Slice) It's variable length , In fact, slicing is a layer of encapsulation based on array types , therefore The slice points to an underlying array . Slice new elements , When the underlying array pointed to by the slice can hold , Then add the element directly , When the underlying array cannot hold new elements , Slicing will automatically follow a certain strategy “ Capacity expansion ”, At this point, the underlying array that the slice points to will be replaced .
Slices have two very important properties , length (len), Capacity (cap), The former is the number of elements that the slice already contains , The latter is the first pointer to the slice ( First element ) The length from the index of the underlying array to the last element of the underlying array .
section Slice
1.C# The generic set of List
According to the characteristics of the slice , The blogger's analogy is C# Generic collection in , There will also be properties such as length and capacity , Including automatic capacity expansion , But bloggers do not know whether the expansion algorithm is consistent , If you are interested in it, you can check it by yourself .
// Instantiation initialization
List<string> ls = new List<string> { " Beijing ", " Shanghai ", " Guangzhou ", " Shenzhen " };
// Output capacity and length
Console.WriteLine($"the capacity of citylist is {ls.Capacity},and the length of citylist is {ls.Count}");
// New elements
ls.Add(" Chengdu ");
// Output capacity and length again
Console.WriteLine($"the capacity of citylist is {ls.Capacity},and the length of citylist is {ls.Count}");
// Remove elements
ls.Remove(" Chengdu ");
// Output capacity and length again
Console.WriteLine($"the capacity of citylist is {ls.Capacity},and the length of citylist is {ls.Count}");
// Traversing elements
foreach (string city in ls)
{
}
the capacity of citylist is 4,and the length of citylist is 4
the capacity of citylist is 8,and the length of citylist is 5
the capacity of citylist is 8,and the length of citylist is 4
In addition to C# There are also many, many extension methods to manipulate generic collections , Here are some common .
// Add multiple elements
public void AddRange(IEnumerable<T> collection);
// Delete all
public void Clear();
// Delete on condition
public int RemoveAll(Predicate<T> match);
// Range deletion by index
public void RemoveRange(int index, int count);
// Traversal operation
public void ForEach(Action<T> action);
// Determine whether there is an element
public bool Contains(T item);
// Judge whether there exists according to the conditions
public bool Exists(Predicate<T> match);
// Find the specified element by criteria
public List<T> FindAll(Predicate<T> match);
// Flip the set
public void Reverse();
// Convert array
public T[] ToArray();
2.Golang Slice in
The slice is not in C# So convenient for generic collections in , Have some hard conditions , For example, allocate space , Few operation functions , But it also reduces the amount of memory , Remember the following general operations , You can basically understand the relevant operations on slices in the source code .
1. initialization - newly added - Copy
1.1 Definition does not initialize
// Definition does not initialize - The uninitialized definition is called - Zero slice
var citySlice0 []string
1.2 Define and initialize
// Define and initialize
var citySlice1 = []string{}
var citySlice2 = []string{" Beijing ", " Shanghai ", " Guangzhou ", " Shenzhen "}
1.3 make Define and initialize
//make Define and initialize
citySlice := make([]string, 4, 10)
fmt.Printf("the citySlice is %v\n", citySlice)
1.4 Capacity and length
By built-in functions cap()len() Provide :
// Output capacity and length
fmt.Printf("the capacity of citySlice is %v,and the length of citySlice is %v \n", cap(citySlice), len(citySlice))
1.5 newly added
By built-in functions append() Provide :
// New elements
citySlice = append(citySlice, " Beijing ", " Shanghai ", " Guangzhou ", " Shenzhen ")
fmt.Printf("the citySlice is %v\n", citySlice)
fmt.Printf("the capacity of citySlice is %v,and the length of citySlice is %v \n", cap(citySlice), len(citySlice))
//var The simplest way to declare a zero value slice is through append The function directly uses , No initialization is required
var intSliceA []int
intSliceA = append(intSliceA, 1, 2, 3)
fmt.Printf("the intSliceA is %v \n", intSliceA)//[1 2 3]
// Slicing is a reference type A simple assignment results in the following
intSliceB := intSliceA
intSliceB[0] = 0
fmt.Printf("the intSliceA is %v \n", intSliceA) //[0,2,3]
1.6 Copy
By built-in functions copy() Provide :
// In order not to affect the assignment operation , Only by copying the slice can the desired effect be achieved , But copy one slice to another , The target slice needs to allocate space
intSliceC := make([]int, 4, 5)
copy(intSliceC, intSliceA)
fmt.Printf("the intSliceC is %v \n", intSliceC) //[0 2 3 0] The first 4 Elements 0, Because of the allocation of space , All are zero values
intSliceC[0] = 10
fmt.Printf("the intSliceA is %v \n", intSliceA) //[0 2 3]
fmt.Printf("the intSliceC is %v \n", intSliceC) //[10 2 3 0]
1.7 Summary
// Definition does not initialize - The uninitialized definition is called - Zero slice
var citySlice0 []string
// Define and initialize
var citySlice1 = []string{}
var citySlice2 = []string{" Beijing ", " Shanghai ", " Guangzhou ", " Shenzhen "}
//make Define and initialize
citySlice := make([]string, 4, 10)
fmt.Printf("the citySlice is %v\n", citySlice)
// Output capacity and length
fmt.Printf("the capacity of citySlice is %v,and the length of citySlice is %v \n", cap(citySlice), len(citySlice))
// New elements
citySlice = append(citySlice, " Beijing ", " Shanghai ", " Guangzhou ", " Shenzhen ")
fmt.Printf("the citySlice is %v\n", citySlice)
fmt.Printf("the capacity of citySlice is %v,and the length of citySlice is %v \n", cap(citySlice), len(citySlice))
// New elements
citySlice = append(citySlice, " Chengdu ", " wuhan ")
fmt.Printf("the citySlice is %v\n", citySlice)
fmt.Printf("the capacity of citySlice is %v,and the length of citySlice is %v \n", cap(citySlice), len(citySlice))
//var The simplest way to declare a zero value slice is through append The function directly uses , No initialization is required
var intSliceA []int
intSliceA = append(intSliceA, 1, 2, 3)
fmt.Printf("the intSliceA is %v \n", intSliceA)//[1 2 3]
// Slicing is a reference type A simple assignment results in the following
intSliceB := intSliceA
intSliceB[0] = 0
fmt.Printf("the intSliceA is %v \n", intSliceA) //[0,2,3]
// In order not to affect the assignment operation , Only by copying the slice can the desired effect be achieved , But copy one slice to another , The target slice needs to allocate space
intSliceC := make([]int, 4, 5)
copy(intSliceC, intSliceA)
fmt.Printf("the intSliceC is %v \n", intSliceC) //[0 2 3 0] The first 4 Elements 0, Because of the allocation of space , All are zero values
intSliceC[0] = 10
fmt.Printf("the intSliceA is %v \n", intSliceA) //[0 2 3]
fmt.Printf("the intSliceC is %v \n", intSliceC) //[10 2 3 0]
the citySlice is [ ]
the capacity of citySlice is 10,and the length of citySlice is 4
the citySlice is [ Beijing Shanghai Guangzhou Shenzhen ]
the capacity of citySlice is 10,and the length of citySlice is 8
the citySlice is [ Beijing Shanghai Guangzhou Shenzhen Chengdu wuhan ]
the capacity of citySlice is 10,and the length of citySlice is 10
the intSliceA is [1 2 3]
the intSliceA is [0 2 3]
the intSliceC is [0 2 3 0]
the intSliceA is [0 2 3]
the intSliceC is [10 2 3 0]
2. cut
Slicing is called slicing , Focus on cutting
“ Array UPCUT , It becomes a slice , Cut into slices , It becomes slicing (#^.^#), Of course not. , It's still called slicing .”
//the intSliceC is [10 2 3 0]
// From the index 1 Cut to the end
intSliceD := intSliceC[1:]
fmt.Printf("the intSliceD is %v \n", intSliceD) // [2 3 0]
// From the index 1 Cut to index 2, According to mathematical knowledge, it is left closed and right open [1,3)
intSliceE := intSliceC[1:3]
fmt.Printf("the intSliceE is %v \n", intSliceE) //[2 3]
// From the index 0 Cut to n-1 0,1,2
intSliceF := intSliceC[:3]
fmt.Printf("the intSliceF is %v \n", intSliceF) //[10 2 3]
// Verify the length and capacity again
fmt.Printf("the capacity of intSliceF is %v,and the length of intSliceF is %v \n", cap(intSliceF), len(intSliceF))
//
fmt.Printf("the intSliceC is %v \n", intSliceC) //[10 2 3 0]
the intSliceD is [2 3 0]
the intSliceE is [2 3]
the intSliceF is [10 2 3]
the capacity of intSliceF is 5,and the length of intSliceF is 3
the intSliceC is [10 2 3 0]
3. Delete
golang Is a direct delete function that does not provide slicing , But you can use the built-in append() function
func append(slice []Type, elems ...Type) []Type
ps: Variable parameters are used in parameters
... Type, Is similar to the C# Variable parameters inparams T[] x,C#Internally, it is converted to array processing ,GolangInternal conversion to slice . There is a little difference , That is, if the parameter is passed to the slice , We need to add..., Other usage and C# Agreement
intSliceC = append(intSliceC[:1], intSliceC[2:]...)
fmt.Printf("the intSliceC is %v \n", intSliceC) // [10 2 0]
fmt.Printf("the capacity of intSliceC is %v,and the length of intSliceC is %v \n", cap(intSliceC), len(intSliceC))
the intSliceC is [10 2 0]
the capacity of intSliceC is 5,and the length of intSliceC is 3
4. Determine whether the slice is empty
Only use len function , Out of commission nil.
len(s) == 0
5. Traverse
s := []int{1, 3, 5}
for i := 0; i < len(s); i++ {
fmt.Println(i, s[i])
}
for index, value := range s {
fmt.Println(index, value)
}
0 1
1 3
2 5
0 1
1 3
2 5
Again : This series is not a tutorial , If you want to learn systematically , Bloggers can recommend learning resources .
边栏推荐
- What conditions do you need to meet to fight new debts? Is it safe to fight new debts
- 宝安区航城街道领导一行莅临联诚发参观调研
- RStudio 1.4软件安装包和安装教程
- Deeply understand and grasp the basic characteristics of digital economy
- TCP/UDP基本原理
- Daily question brushing record (II)
- What are the requirements for new bonds? Is it safe to play new bonds
- Eight misunderstandings, broken one by one (final): the cloud is difficult to expand, the customization is poor, and the administrator will lose control?
- Emmet语法规范
- 【Golang】怎么实现Go程序的实时热更新
猜你喜欢

Use of the vs2022scanf function. An error is reported when using scanf - the return value is ignored: Solutions

基于SSM实现微博系统

Ugeek's theory 𞓜 application and design of observable hyperfusion storage system

SQL联合查询(内联、左联、右联、全联)的语法

Tcp/udp Fundamentals

为什么你的数据图谱分析图上只显示一个值?

Flagai Feizhi: AI basic model open source project, which supports one click call of OPT and other models

After the collapse of UST, will the stable currency market pattern usher in new opportunities?

Check four WiFi encryption standards: WEP, WPA, WPA2 and WPA3

Open source SPL redefines OLAP server
随机推荐
Development notes of wedding studio applet based on wechat applet
How to write a great online user manual in 7 steps
Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181
SQL聯合查詢(內聯、左聯、右聯、全聯)的語法
Elastricearch's fragmentation principle of the second bullet
基于 ShardingSphere 的得物数据库中间件平台“彩虹桥”演进之路
UGeek大咖说 | 可观测之超融合存储系统的应用与设计
直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践
「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能
JDBC 在性能測試中的應用
Ready to migrate to the cloud? Please accept this list of migration steps
MySQL时间函数的运用,简单问题
TCP/UDP基本原理
How to avoid the "black swan" incident in the gene field: a security war behind a preventive "recall"
Official announcement. Net 7 preview 5
Zabbix监控- Aruba AP运行数据
Add two factor authentication, not afraid of password disclosure, let alone 123456
GL Studio 5 安装与体验
GaussDB(DWS) 数据库智能监控运维服务-节点监控指标
Can the biggest gamefi crash victim survive the bear market in May| May Monthly Report