by ericbb · 13y ago · 0 comments
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