I am trying to port a hash function from C to Go using unsafe.Pointer
. I need to get the pointer to the first character of the key string.
I tried &(hello[0])
and &hello[0]
and failed.
I am trying to port a hash function from C to Go using unsafe.Pointer
. I need to get the pointer to the first character of the key string.
I tried &(hello[0])
and &hello[0]
and failed.
string
values in Go are immutable, and therefore not addressable; so you cannot take the address of its runes or bytes. If you could, you could modify the pointed value and thus modify the content of the string
value. In Go there is also no pointer arithmetic.
What you can do is simply index the string
, indexing a string
indexes its bytes (in UTF-8 encoded form, this is how Go stores string
values in memory). You can "mimic" the pointer arithmetic with "index arithmetic".
See this example:
s := "Hello World"
i := 0
fmt.Println(s[i], string(s[i]))
i += 4
fmt.Println(s[i], string(s[i]))
Output (try it on the Go Playground):
72 H
111 o
You may also convert the string
to a []byte
or []rune
, should you have the need to do so (e.g. if you need to modify the bytes), and you can work with that. Slices are also addressable. Note that converting a string
value to the mentioned slice types will make a copy of the string
content (to preserve the immutability of the string
).
While it's the rune
type that represents a Unicode character, if you're trying to reproduce a hash algorithm, you most likely want to work with bytes, so convert it to a byte slice (which is the UTF-8 encoded byte sequence of the string
):
s := "Hello World"
b := []byte(s)
// Here you can work with b which is addressable
Note that in Go, the types byte
and uint8
are "identical", byte
is an alias for uint8
, you can also write:
s := "Hello World"
b := []uint8(s)
In golang string it's a massive of bytes, need convert string to rune
package main
import (
"fmt"
)
func test(r *rune) {
*r = rune('L')
}
func main() {
s := []rune("Hello")
fmt.Println(string(s))
fmt.Println(&s[0])
test(&s[0])
fmt.Println(string(s))
}