Skip to content

Doubt about behaviour of unsafe.Pointer when converting string to int32 #42046

@andreleoni

Description

@andreleoni

What version of Go are you using (go version)?

PS C:\Users\cliente\Desktop\gostudies> go version
go version go1.15.3 windows/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

go env Output
$ go env

What did you do?

I'm studying about the unsafe.Pointer when working with pointers.

I looked that the unsafe.Pointer should return a float, or an int into another format, for example:

If I have an int64 variable pointer, I should transform into int32 by the (*int32)(unsafe.Pointer(t.value)) usage.

package main

import (
	"fmt"
	"unsafe"
)

type test struct {
	value *int64
}

func main() {
	var v int64
	v = 123
	t := test{&v}

	var ptest = (*int32)(unsafe.Pointer(t.value))
	fmt.Println(ptest)
	fmt.Println(*ptest + 10)
}

This is good behavior.

So, I tried to change the int32 of the unsafe.Pointer to string like this function:

package main

import (
	"fmt"
	"unsafe"
)

type test struct {
	value *string
}

func main() {
	var v string
	v = "123"
	t := test{&v}

	var ptest = (*int32)(unsafe.Pointer(t.value))
	fmt.Println(ptest)
	fmt.Println(*ptest + 10)
}

When I did it, I am getting the following response from execution:

PS C:\Users\cliente\Desktop\gostudies> go run main.go
0xc00004a1f0
17736171

What did you expect to see?

I expected to convert my "123" to 123 integer to sum with my 10 number.

What did you see instead?

This number 17736171 is a "random" number.

What does the 17736171 meaning in this case?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions