Home>Article>Backend Development> How to delete slices in go language
go languageMethod to delete slices: First create a go sample file; then declare variables; finally pass "ss=append(ss[:index],ss[index 1:]. ..)print("after delete",ss)" can be used to delete slice elements.
The operating environment of this tutorial: Windows 7 system, Go version 1.14, Dell G3 computer.
1. Declare variables, go automatically initializes to nil, length: 0, address: 0, nil
func main(){ var ss []string; fmt.Printf("length:%v \taddr:%p \tisnil:%v",len(ss),ss, ss==nil) } --- Running... length:0 addr:0x0 isnil:true Success: process exited with code 0.
2. Add, delete, insert operations of slices
func main(){ var ss []string; fmt.Printf("[ local print ]\t:\t length:%v\taddr:%p\tisnil:%v\n",len(ss),ss, ss==nil) print("func print",ss) //切片尾部追加元素append elemnt for i:=0;i<10;i++{ ss=append(ss,fmt.Sprintf("s%d",i)); } fmt.Printf("[ local print ]\t:\tlength:%v\taddr:%p\tisnil:%v\n",len(ss),ss, ss==nil) print("after append",ss) //删除切片元素remove element at index index:=5; ss=append(ss[:index],ss[index+1:]...) print("after delete",ss) //在切片中间插入元素insert element at index; //注意:保存后部剩余元素,必须新建一个临时切片 rear:=append([]string{},ss[index:]...) ss=append(ss[0:index],"inserted") ss=append(ss,rear...) print("after insert",ss) } func print(msg string,ss []string){ fmt.Printf("[ %20s ]\t:\tlength:%v\taddr:%p\tisnil:%v\tcontent:%v",msg,len(ss),ss, ss==nil,ss) fmt.Println() } ------ Running... [ local print ] : length:0 addr:0x0 isnil:true [ func print ] : length:0 addr:0x0 isnil:true content:[] [ local print ] : length:10 addr:0xc208056000 isnil:false [ after append ] : length:10 addr:0xc208056000 isnil:false content:[s0 s1 s2 s3 s4 s5 s6 s7 s8 s9] [ after delete ] : length:9 addr:0xc208056000 isnil:false content:[s0 s1 s2 s3 s4 s6 s7 s8 s9] [ after insert ] : length:10 addr:0xc208056000 isnil:false content:[s0 s1 s2 s3 s4 inserted s6 s7 s8 s9] Success: process exited with code 0.
Recommended: "go Language Tutorial"
The above is the detailed content of How to delete slices in go language. For more information, please follow other related articles on the PHP Chinese website!