MST

星途 面试题库

面试题:Go语言中bytes包如何实现简单的字节查找

在Go语言的bytes包中,有多种函数可用于字节查找。请使用`bytes.Index`函数编写一个函数,该函数接收两个字节切片`haystack`和`needle`作为参数,返回`needle`在`haystack`中第一次出现的位置。如果`needle`不在`haystack`中,则返回 -1。
17.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "bytes"
    "fmt"
)

func findNeedleInHaystack(haystack, needle []byte) int {
    return bytes.Index(haystack, needle)
}

你可以通过如下方式调用:

func main() {
    haystack := []byte("hello world")
    needle := []byte("world")
    result := findNeedleInHaystack(haystack, needle)
    fmt.Println(result) 
}