Reputation: 39
I have a *int64
as one of the parameters in my function, and I need to convert it to *int32
to meet the definition of the function I want to call.
func t1(x *int64) error {
var y *int32
t2(y)
}
func t2(y *int32) error {}
And, if I want to convert *int32
to *int8
, then do I need another function? Is there a way to handle such problems?
Upvotes: 2
Views: 4214
Reputation: 1219
Now, Golang has generic types which can help you to have a generic converting function:
type IntNumber interface {
int | int8 | int16 | int32 | int64
}
func IntNumberPointersToPointers(T IntNumber, K IntNumber)(from *T) *K {
if from == nil {
return nil
}
result := K(*from)
return &result
}
You can call the function by:
// The result will be int
input := int32(100)
result := util.IntNumberPointersToPointers[int32, int](&input)
Go playground: https://go.dev/play/p/sRP17iFX6J6
Assume that you are aware about converting big int to smaller may cause data loss. E.g int64
to int32
Upvotes: 0
Reputation: 42413
[H]ow to convert *int64 to *int32?
You cannot.
Use var i32 int32 = int32(*x); t2(&i32); *x=int64(i32)
.
Upvotes: 2