【go】Slice interception summary

1. Get the i-th element of the slice

func main() {
    
    
	s := []int{
    
    1, 2, 3, 4, 5}
	fmt.Println("第一个元素为:", s[0])
	fmt.Println("最后一个元素为:", s[len(s)-1])
	fmt.Println("倒数第二个元素为:", s[len(s)-2])
}

2. Get the i-th to j-th elements of the slice

func main() {
    
    
	s := []int{
    
    1, 2, 3, 4, 5}
	fmt.Println("从索引2到最后的全部元素:", s[2:])
	// 3 4 5
	fmt.Println("从索引0到索引2的全部元素:", s[:2])
	// 0 1 2
	fmt.Println("从索引2到索引4的全部元素:", s[2:3:3])
	// 3 4
}

3. Various slicing and interception operations

operate meaning
s[n] The item at index position n in slice s
s[:] The slice obtained from index position 0 of slice s to len(s)-1
s[low:] The slice obtained from the index position low of slice s to len(s)-1
s[:high] The slice obtained from the index position 0 of slice s to high, len=high
s[low:high] The slice obtained from the index position low to high of slice s, len=high-low
s[low :high : max] The slice obtained from the index position low to high of slice s, len=high-low, cap=max-low
only The length of slice s, always <=cap(s)
cap(s) The capacity of slice s, always >=len(s)

Guess you like

Origin blog.csdn.net/qq_45859826/article/details/132587061