当前位置:网站首页>[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 .
边栏推荐
- How to install SSL certificates in Microsoft Exchange 2010
- How do I open an account? Is it safe to open an account in Guohai Securities? What do you need to bring?
- Ready to migrate to the cloud? Please accept this list of migration steps
- Yaokui tower in Fengjie, Chongqing, after its completion, will be the safety tower for Sichuan river shipping with five local scholars in the company
- Shell Scripting
- 区块哈希竞猜游戏系统开发(dapp)
- 如何利用数仓创建时序表
- 教你如何用网页开发桌面应用
- 硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
- 【Golang】快速复习指南QuickReview(一)——字符串string
猜你喜欢

The golden nine silver ten, depends on this detail, the offer obtains the soft hand!

20 provinces and cities announce the road map of the meta universe

基于SSM实现微博系统

Hardware development notes (6): basic process of hardware development, making a USB to RS232 module (5): creating USB package library and associating principle graphic devices

金九银十,靠这个细节,offer拿到手软!

Yaokui tower in Fengjie, Chongqing, after its completion, will be the safety tower for Sichuan river shipping with five local scholars in the company

ElastricSearch第二弹之分片原理

FPGA based electromagnetic ultrasonic pulse compression detection system paper + source file

Implementation of microblog system based on SSM

What are the useful personnel management software? Personnel management system software ranking!
随机推荐
35 year old crisis? It has become a synonym for programmers
数字化采购转型解决方案:SaaS采购管理平台推进企业阳光采购
Deeply understand and grasp the basic characteristics of digital economy
SQL联合查询(内联、左联、右联、全联)的语法
国元期货交易软件正规吗?如何安全下载?
@@Script implementation of ishell automatic deployment
Can the biggest gamefi crash victim survive the bear market in May| May Monthly Report
vs2022scanf函数的使用,使用scanf的报错-返回值被忽略:解决·方法
Implementing MySQL fuzzy search with node and express
Implementation of microblog system based on SSM
Syntax of SQL union query (inline, left, right, and full)
Interpreting the 2022 agile coaching industry status report
区块哈希竞猜游戏系统开发(dapp)
RStudio 1.4软件安装包和安装教程
官宣.NET 7 预览版5
科班出身,结果外包都不要
怎么开户?在国海证券开户安全吗?需要带什么?
为什么你的数据图谱分析图上只显示一个值?
Are internal consultants and external consultants in SAP implementation projects difficult or successful?
Check four WiFi encryption standards: WEP, WPA, WPA2 and WPA3