preface

There is a type in Golang called slice, often referred to as slice. So this time let’s look at the basic usage of slicing

define

In the GO language, a slice definition looks like this:

var identifier []int
Copy the code

It is worth noting that the variable that defines the method above is nil, which can also be created directly like this:

identifier := make([]int.0)
Copy the code

You can also specify the initial size of the slice:

identifier := make([]int.0.10)
Copy the code

You can also abbreviate:

identifier := []int{}
Copy the code

Slice from array:

arr := [5]int{0.1.2.3.4}
identifier := arr[1:3]
Copy the code

operation

Add elements

Append elements to golang, using the keyword append to add sliced elements:

func main(a) {
        s := make([]int.0.0)
        s = append(s, 1.2.3.4)
        fmt.Println(s)
}
Copy the code

The output is:

[1, 2, 3, 4]Copy the code

Members of the change

func main(a) {
	s := make([]int.0.0)
	s = append(s, 1.2.3.4)
	fmt.Printf("Before change to: %v\n", s)
	s[0] = 5
	fmt.Printf("Changed to: %v\n", s)
}
Copy the code

The output is:

Before the change, it was [1 2 3 4]. After the change, it was [5 2 3 4].Copy the code

Get member

func main(a) {
	s := []int{1.2.3.4.5}
	fmt.Printf(The first element is: %d\n, s[1])
	fmt.Printf(The penultimate element is: %d\n, s[len(s)2 -:len(s)- 1] [0])
	fmt.Printf("The last element is: %d\n", s[len(s) - 1])
	fmt.Printf("The last element is: %d\n", s[len(s)- 1:] [0])}Copy the code

append

Note that if the size of the slice exceeds the original limit, the underlying array will be reallocated, so the pointer address of the slice will also change:

func main(a) {
	s := []int{1.2.3.4.5}
	fmt.Printf("S original address: %p\n", s)
	s = append(s, 6.7.8)
	fmt.Printf("%p\n", s)

	s2 := make([]int.0.3)
	fmt.Printf("S2 defines the original address as: %p\n", s2)
	s2 = append(s2, 1.2.3)
	fmt.Printf("S2: %p\n", s2)
	s2 = append(s2, 4.5.6)
	fmt.Printf("S2: %p\n", s2)
}
Copy the code

The output is:

S Original address: 0xC000016120 S Address with added elements: 0xC000018140 S2 Original address: 0xC00001A1e0 S2 Address with added capacity elements: 0xC00001a1e0 S2 Address with added capacity elements: 0xC00001A1e0 0xc000016150Copy the code

Afterword.

There are many more uses for slicing, but this article lists only the most basic ones, step by step.

Finally, thank you for reading, thank you!