package main
import "fmt"
/*
Author: Guo
Date: 3/16/21 2:24 PM
Description:
Company:
Updated: ??@??@?? ????
*/
//方式一:使用copy()
func removeSample1(in []interface{}, index int) ([]interface{}, bool) {
if len(in) == 0 || index < 0 {
return in, false
}
if len(in)-1 == index {
return in[:len(in)-1], true
}
if len(in)-1 < index {
return in, false
}
copy(in[index:], in[index+1:])
return in[:len(in)-1], true
}
//方式二:使用append()
func removeSample2(in []interface{}, index int) ([]interface{}, bool) {
if len(in) == 0 || index < 0 {
return in, false
}
if len(in)-1 == index {
return in[:len(in)-1], true
}
if len(in)-1 < index {
return in, false
}
return append(in[:index], in[index+1:]...), true
}
func main() {
in1 := make([]interface{}, 0)
fmt.Println(removeSample2(in1, -1))
fmt.Println(removeSample2(in1, 0))
in2 := []interface{}{1}
fmt.Println(removeSample2(in2, -1))
fmt.Println(removeSample2(in2, 0))
fmt.Println(removeSample2(in2, 1))
in3 := []interface{}{1, 2, 3, 4}
fmt.Println(removeSample2(in3, 0))
in4 := []interface{}{1, 2, 3, 4}
fmt.Println(removeSample2(in4, 1))
in5 := []interface{}{1, 2, 3, 4}
fmt.Println(removeSample2(in5, 2))
}
//其中返回的bool值表示要删除的元素是否存在
执行结果:
[] false
[] false
[1] false
[] true
[1] false
[2 3 4] true
[1 3 4] true
[1 2 4] true