In my case, I have 2 variables with data types as *uint64
and *uint32
. I need to convert them to the int
data type.
When I try to convert them with int()
function, it raise such error:
Cannot convert an expression of type *uint64 to type int.
I notice that the same int()
function works without any problem if data types don't have * (asterisk)
character.
So my question is how correctly convert *uint64
and *uint32
data types to the int
data type?!
You can't (shouldn't) convert a pointer to int
, what you most likely want to do is convert the pointed value to int
.
So simply dereference the pointer to get an uint64
and uint32
value, which you can convert:
var i *uint64 = new(uint64)
var j *uint32 = new(uint32)
*i = 1
*j = 2
var k, l int
k = int(*i)
l = int(*j)
fmt.Println(k, l)
This outputs (try it on the Go Playground ):
1 2
Note that of course if the pointer is nil
, attempting to dereference it (like *i
) results in a runtime panic.
Also note that the the size (and thus the valid range) of int
is platform dependent, it may be 64 and 32 bit. Thus converting any uint64
value to int
may lose the upper 32 bits, and certain positive input numbers may turn into negative ones.
[H]ow correctly convert *uint64 and *uint32 data types to the int data type?!
Like this
var a = int64(123)
var pa *uint64 = &a
var i = int(uintptr(unsafe.Pointer(&a)))
But note that while this is the "most correct way" to convert a *uint64 to int but that is almost certainly not what you want to do. What you should do: Learn the language and its type system and try to understand what pointer values are.
(Note the "most correct" as there are no correct ways to do what you asked.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.