go語言刪除切片的方法:先建立一個go範例檔;然後宣告變數;最後透過「ss=append(ss[:index],ss[index 1:]. ..)print("after delete",ss)”方式刪除切片元素即可。
本教學操作環境:Windows7系統、Go1.14版,Dell G3電腦。
1.宣告變量,go自動初始化為nil,長度:0,位址: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.切片的追加,刪除,插入操作
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.
推薦:《go語言教學》
以上是go語言如何刪除切片的詳細內容。更多資訊請關注PHP中文網其他相關文章!