当前位置:网站首页>[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 in params T[] x,C# Internally, it is converted to array processing ,Golang Internal 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 .

原网站

版权声明
本文为[DDGarfield]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231850564573.html