I'm trying to write Go generic function, which accepts a value of signed integer type and returns result having corresponding unsigned type.
C++11 provides special template for this case:
#include <type_traits>
...
template <typename T>
typename std::make_unsigned<T>::type fooBar(T value) {
...
}
auto fb = fooBar(4LL); // parameter is long long, result is unsigned long long
Is there any posibility to do this in Go? If not, are there any workarounds? At least, are there any proposals for such facilities in Go?
Unfortunately you can't do the exact same thing in Go. However there is workaround yes (but it is less elegant imo).
First you should define a structure:
type Unsigned[T constraints.Integer] struct {
val T
}
func (u Unsigned[T]) Unsigned() uint64 {
return uint64(u.val)
}
func (u Unsigned[T]) InitialValue() T {
return u.val
}
Then your function should looks like:
func fooBar[T constraints.Integer](val T) Unsigned[T] {
// ...
return Unsigned[T]{val: val}
}
However, this will just make a std::reinterpret_cast
equivalent. If you want only positive value returned you can keep the constraints.Integer
constraint but just add a condition that check if the value is < 0
.
If you wanted unsigned integer only in the first place you have constraints.Unsigned
constraint.
(see on go playground: https://go.dev/play/p/uAyd5_c8i0L?v=)
I don't know if I really helped you but don't hesitate to tell me more about what you are trying to do so we can see together if there is a good way to do it in Go ^^