* [email protected] <[email protected]> [180225 11:37]:
> I think I get it.
> Because the above program tries to modify the constant (or program) zone,
> which is not allowed.
> The following program works:
But, note that the language spec does not guarantee it to work. The
compiler is free to recognize what that first line is doing and optimize
the assignment into a string in a R/O memory segment. The optimization
is legal because the compiler does not have to recognize the use of
unsafe to determine the programmer's intent to subvert the type system.
> package main
>
> import "fmt"
> import "unsafe"
> import "reflect"
>
> func main() {
> s := string([]byte{'k', 'e', 'e', 'p'})
> hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
> byteSequence := (*byte)(unsafe.Pointer(hdr.Data))
> fmt.Println(string(*byteSequence)) // k
> *byteSequence = 'j' // crash here
> fmt.Println(s) // expect: jeep
> }
...Marvin
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.