On Wed, Mar 28, 2018 at 9:04 AM, Nilsocket <nilsoc...@gmail.com> wrote:
>
> package main
>
> import (
>     "fmt"
>     "unsafe"
> )
>
> func main() {
>     showString("12345")
> }
>
> func showString(s string) {
>     res := *(*[unsafe.Sizeof(s)]byte)(unsafe.Pointer(&s))
>     fmt.Println(s, res, []byte(s))
>     for i := range res {
>         fmt.Printf("%.2x", res[i])
>     }
>     fmt.Println()
> }
>
> //Output:
> // 12345 [205 84 75 0 0 0 0 0 5 0 0 0 0 0 0 0] [49 50 51 52 53]
> // cd544b00000000000500000000000000
>
> If I change fmt.Printf("%.2x ",res[i])
>     for i := range res {
>         fmt.Printf("%.2x ", res[i])
>     }
> //Output:
> // 12345 [206 84 75 0 0 0 0 0 5 0 0 0 0 0 0 0] [49 50 51 52 53]
> // ce 54 4b 00 00 00 00 00 05 00 00 00 00 00 00 00
>
> Ouput changes, why is it, like that?
>
> How Strings are actually represented in go?(underlying representation)

https://research.swtch.com/godata


> When type casting, why unsafe.Sizeof(x), is accepted as size, but not
> someother function which returns the same value with same type.
>
> res := *(*[si(s)]byte)(unsafe.Pointer(&s)) //This is not valid, non-constant
> array bound
>
> func si(s string) uintptr {
>     return unsafe.Sizeof(s)
> }
>
> But works completely fine for unsafe.Sizeof(s).

Because in Go the size of an array must be a constant.

Ian

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to