I have the following function, it works flawlessly
func (r *system) Quantity() int32 {
// r.info.Quantity is type int
return int32(r.info.Quantity)
}Now I'm trying to cast it to *int32
func (r *system) Quantity() *int32 {
// r.info.Quantity is type int
return int32(&r.info.Quantity)
}
But i get the following error cannot use &r.info.Quantity (type *int) as type *int32 in return argument, and of course it seems logic...is there a way to achieve this?
tbh, this raises confusing if you were programming in java or cpp
https://golang.org/pkg/builtin/#int
int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.
Surprised no one mentioned that int usually has 64 bits on 64-bit systems and 32 bits on 32-bit systems. The distinction from both int32 and int64 is clear.
This is possibly a stupid question, but I come from JS and i just started learning GO. Now as you may know in JS everything is Number but in GO there are int, int8, 32, 64. So, I was wandering should i get in habit of using specific int type or just use int in 99% of cases? What’s the advantage and when do you guys use it in real life if you do?
I have a field in my data which is small enough to simply use an int32. However, from what I can tell, int32 is generally used when representing a code point or something quite specific, rather than using it simply to save 32 bits of storage. Also, some of the stdlib packages (like strconv) deal exclusively with int64 rather than int32. This has meant changes to my code I didn't expect purely to handle int32 things.
What is your opinion (and perhaps the general consensus) on using int32 purely for efficiency purposes? Is it just worth using an int64 for simplicity?
You convert them with a type "conversion"
var a int
var b int64
int64(a) < b
When comparing values, you always want to convert the smaller type to the larger. Converting the other way will possibly truncate the value:
var x int32 = 0
var y int64 = math.MaxInt32 + 1 // y == 2147483648
if x < int32(y) {
// this evaluates to false, because int32(y) is -2147483648
Or in your case to convert the maxInt int64 value to an int, you could use
for a := 2; a < int(maxInt); a++ {
which would fail to execute correctly if maxInt overflows the max value of the int type on your system.
I came here because of the title, "How to convert an int64 to int in Go?". The answer is,
int(int64Var)
Simply Use the int() cast function
The Go Programming Language Specification
Conversions
Conversions are expressions of the form
T(x)whereTis a type andxis an expression that can be converted to typeT.
For example,
size := binary.BigEndian.Uint32(b[4:])
n, err := rdr.Discard(int(size))