bytes.Contains() function is used to check whether subslice is present within another slice in go. It returns true If present else false.
bytes.Contains() function prototype:
func Contains(b, subslice []byte) bool or func Contains(b []byte, subslice []byte) bool Input parameters: b: byte slice subslice: byte subslice subslice will be checked within byte slice b.
bytes.Contains() function return value:
bytes.Contains() function returns true If subslice is present within another slice else false.
Explanation:
1) b := []byte("Jhon is attending coding contest") subslice := []byte("Jhon is attending") Here, subslice is present within b. So It will return true. 2) b := []byte("Jhon is attending coding contest") subslice := []byte("where is he") Here, subslice is not present within b. So It will return false.
Example:
Code 1:
package main import ( "fmt" "bytes" ) func main() { // Subslice is present within another slice b := []byte("Jhon is attending coding contest") subslice := []byte("Jhon is attending") is_subslice_pre := bytes.Contains(b, subslice) fmt.Println("Is subslice present: ", is_subslice_pre) // Subslice is not present within another slice b = []byte("Jhon is attending coding contest") subslice = []byte("where is he") is_subslice_pre = bytes.Contains(b, subslice) fmt.Println("Is subslice present: ", is_subslice_pre) }
Output:
Is subslice present: true Is subslice present: false
Code 2:
package main import ( "fmt" "bytes" ) func main() { // Subslice is present within another slice b := []byte{10, 20, 30, 40} subslice := []byte{20, 30} is_subslice_pre := bytes.Contains(b, subslice) fmt.Println("Is subslice present: ", is_subslice_pre) // Subslice is not present within another slice b = []byte{10, 20, 30, 40} subslice = []byte{50, 60} is_subslice_pre = bytes.Contains(b, subslice) fmt.Println("Is subslice present: ", is_subslice_pre) }
Output:
Is subslice present: true Is subslice present: false
To learn more about golang, Please refer given below link:
References: