go判断slice中是否有元素及查找和删除切片中元素

2023-06-01 00:00:00 元素 查找 切片

在切片中查找元素 示例代码:

package main
import "fmt"

// 查找切片中某个元素是否存在
func find(source []string, value string) bool {
for _, item := range source {
if item == value {
return true
}
}
return false
}

func main() {
source := []string{"san","man","tan"}
result := find(source,"san")
fmt.Printf("Item san found: %t\n",result)

result = find(source, "can")
fmt.Printf("Item can found: %t\n",result)
}

输出:

Item san found: true
Item can found: false


查找和删除切片中元素 示例代码:


package main
import "fmt"

//查找并删除切片中的某个元素是否存在,下面的方法会改变原来的切片
func findAndDelete1(source []int, value int) []int {
index := 0
for _, item := range source {
if item != value {
source[index] = item
index++
}
}
return source[:index]
}
//查找并删除切片中是否存在某个元素,下面的方法不会改变原来的切片
func findAndDelete2(source []int, value int) []int {
var new = make([]int, len(source))
index := 0
for _, item := range source {
if item != value {
new[index] = item
index++
}
}
return new
}

func main() {
before1 := []int{'a', 'b', 'c', 'k', 'a'}
fmt.Printf("before1的操作地址是:%p, before1的元素是:%v\n", &before1, before1)

after1 := findAndDelete1(before1, 'a')
fmt.Printf("after1的操作地址是:%p, after1的元素是:%v\n", &after1, after1)
fmt.Printf("before1的操作地址是:%p, before1的元素是:%v\n", &before1, before1)

fmt.Println()

before2 := []int{'a','b','c','e','a'}
fmt.Printf("before2的操作地址是:%p, before2的元素是:%v\n",&before2,before2)

after2 := findAndDelete2(before2,'a')
fmt.Printf("after2的操作地址是:%p, after2的元素是:%v\n",&after2,after2)
fmt.Printf("before2的操作地址是:%p, before2的元素是:%v\n",&before2,before2)
}


输出:

before1的操作地址是: 0xc000004078, before1的元素是: [97 98 99 107 97]
after1的操作地址是: 0xc0000040a8, after1的元素是: [98 99 107]
before1的操作地址是: 0xc000004078, before1的元素是: [98 99 107 107 97]
 
before2的操作地址是: 0xc0000040f0, before2的元素是: [97 98 99 101 97]
after2的操作地址是: 0xc000004120, after2的元素是: [98 99 101 0 0]
before2的操作地址是: 0xc0000040f0, before2的元素是: [97 98 99 101 97]

相关文章