An overview of the
Slice is a dynamic array, more flexible than array operation, the length is not fixed, can be appended and deleted.
Len () and cap() can return the same and different results.
Statement section
//demo_7.go
package main
import (
"fmt"
)
func main() {
Var sli_1 [] int //nil
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_1),sli_1)
Var sli_2 = [] int {
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_1),cap(sli_2),sli_2)
var sli_3 = [] int {1, 2, 3, 4, 5}
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_3),cap(sli_3),sli_3)
sli_4 := [] int {1, 2, 3, 4, 5}
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_4),cap(sli_4),sli_4)
var sli_5 [] int = make([] int, 5, 8)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_5),cap(sli_5),sli_5)
sli_6 := make([] int, 5, 9)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli_6),cap(sli_6),sli_6)
}
Copy the code
Running results:
Intercept slice
//demo_8.go
package main
import (
"fmt"
)
func main() {
sli := [] int {1, 2, 3, 4, 5, 6}
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
fmt.Println("sli[1] ==", sli[1])
fmt.Println("sli[:] ==", sli[:])
fmt.Println("sli[1:] ==", sli[1:])
fmt.Println("sli[:4] ==", sli[:4])
fmt.Println("sli[0:3] ==", sli[0:3])
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3]),cap(sli[0:3]),sli[0:3])
fmt.Println("sli[0:3:4] ==", sli[0:3:4])
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[0:3:4]),cap(sli[0:3:4]),sli[0:3:4])
}
Copy the code
Running results:
Additional section
//demo_9.go
package main
import (
"fmt"
)
func main() {
sli := [] int {4, 5, 6}
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 7)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 8)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 9)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
sli = append(sli, 10)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
}
Copy the code
Running results:
In append, when the capacity is insufficient and needs to be expanded, the CAP is doubled.
Delete slices
//demo_10.go
package main
import (
"fmt"
)
func main() {
sli := [] int {1, 2, 3, 4, 5, 6, 7, 8}
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
// Delete the last two elements
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[:len(sli)-2]),cap(sli[:len(sli)-2]),sli[:len(sli)-2])
// Delete the first two elements
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli[2:]),cap(sli[2:]),sli[2:])
// Delete the middle two elements
sli = append(sli[:3], sli[3+2:]...)
fmt.Printf("len=%d cap=%d slice=%v\n",len(sli),cap(sli),sli)
}
Copy the code
Running results:
Recommended reading
-
Go – array
-
Go – Variable declaration
-
Go – Environment installation
This article is welcome to forward, forward please indicate the author and source, thank you!