go judge whether there is an element in the slice_Golang slice (Slice)

Find an element in a slice


package main
import "fmt"
 
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)
}
// 查找切片中某个元素是否存在
func find(source []string, value string) bool {
	for _, item := range source {
		if item == value {
			return true
		}
	}
	return false
}

operation result:

Item san found: true
Item can found: false

Find and delete an element

package main
import "fmt"
 
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)
}
 
// Find and delete whether an element in the slice exists, the following method will change the original slice
func findAndDelete1(source []int, value int) []int {
	index := 0
	for _, item := range source {
		if item != value {
			source[index] = item
			index++
		}
	}
	return source[:index]
}
// Find and delete whether an element in the slice exists, the following method will not change the original slice
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
}

operation result:

The operation address of before1 is: 0xc000004078, the element of before1 is: [97 98 99 107 97]
The operation address of after1 is: 0xc0000040a8, and the element of after1 is: [98 99 107]
The operation address of before1 is: 0xc000004078, and the element of before1 is: [98 99 107 107 97]
 
The operation address of before2 is: 0xc0000040f0, and the element of before2 is: [97 98 99 101 97]
The operation address of after2 is: 0xc000004120, and the element of after2 is: [98 99 101 0 0]
The operation address of before2 is: 0xc0000040f0, and the element of before2 is: [97 98 99 101 97]

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish