I'm writing vector.go
as a part of my program. It provides a three-dimensional vector
struct and some vector operations.
For symmetry with the general vector
type, I would like to provide a scalar
type:
type scalar float64
I like this because there's no reason I should specify the precision of my scalars each and every time. The fact that they are 64-bit is a detail which I would rather specify only once.
The only problem is that I know this is not like typedef
in C. There seems to be more going on behind the scenes then that. My question: will this incur any overhead? If so, when and how much? Can I use this when performance is absolutely critical? (Assume that I will replace every occurrence of float64
with scalar
and convert literals, e.g, scalar(1.0)
.)
Type aliasing refers to the technique of providing an alternate name for an existing type. Type aliasing was introduced in Go version 1.9 and above. This helps to facilitate code refactor for large codebases.
Type aliases Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead. It's useful to shorten long generic types. For instance, it's often tempting to shrink collection types: typealias NodeSet = Set<Network.
First of all, there is no need to convert literals. x = 1.0
is the same as x = scalar(1.0)
assuming x already has the type scalar.
In Go, there is no such thing as a user defined type alias. In Go, byte and uint8 (which are builtin types) are considered aliases of each other. They are two names for the same type. Float64 and scalar are not the same type. Values of float64 and scalar need to be converted between each other using something like s = scalar(f)
while byte and uint8 do not.
However, such conversions have no overhead. The types are enforced at compile time for code correctness but does not affect performance during execution. Execution is only affected if you do type assertions or use reflection. However, these differences affect logic, not performance.
Can I use this when performance is absolutely critical?
Yes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With