32 ms·
Incidentally, I don't think it's entirely true that "there isn't any pointer math". I've never used it but I understand that you can do C-like pointer tricks by
by ericbb 14y ago
Incidentally, I don't think it's entirely true that "there isn't any pointer math". I've never used it but I understand that you can do C-like pointer tricks by using the package called "unsafe": http://golang.org/pkg/unsafe/ http://golang.org/pkg/unsafe/ and http://golang.org/ref/spec#Package_unsafe http://golang.org/ref/spec#Package_unsafe
- dchest 14y agoYes, 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