Question

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).)

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top