Hacker News new | past | comments | ask | show | jobs | submit login

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




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: