6 ms·
Yes, indeed. Here's the "canonical" C strlen translated to unsafe Go with pointer arithmetic: package main import ( "fmt" "unsafe" ) func s
by dchest 14y ago
Yes, indeed. Here's the "canonical" C strlen translated to unsafe Go with pointer arithmetic:
package main
import (
"fmt"
"unsafe"
)
func strlen(b []byte) int {
str := uintptr(unsafe.Pointer(&b[0]))
s := str
for ; *(*byte)(unsafe.Pointer(s)) != 0; s++ {}
return int(s - str)
}
func main() {
fmt.Println(strlen([]byte("ho ho ho\000")))
}
Not that anyone should use it :-)
The safe and readable variant of this, often used in Go code, is "slice arithmetic", like this: http://golang.org/src/pkg/crypto/sha256/sha256.go#L105 http://golang.org/src/pkg/crypto/sha256/sha256.go#L105