3 ms·
Say you need a Vector2D type: struct Vector2D int x int y Except, hold on, I have a routine that needs floats. In a dynamic language, I'd l
by one-more-minute 12y ago
Say you need a Vector2D type:
struct Vector2D
int x
int y
Except, hold on, I have a routine that needs floats. In a dynamic language, I'd leave off the type hints; with a decent type system I'd parametise the `int` type; in Go I have to reimplement the whole type:
type Vector2DFloat
float x
float y
Lather, rinse and repeat for complex numbers, vectors of vectors, etc. The only way around this is (a) to use the `interface{}` type (in which case you're just using a very verbose dynamic language) or (b) to rely on lots of text-based code generation.
- nadams 12y agoMaybe my brain hasn't starting firing on all cylinders yet this morning...but are you saying that: If I have some function in Go (pseudocode - I don't know Go but it should get my point across) f(float x) { } and call f(vec.x) Go can't cast it to a float? I'm not being sarcastic or anything - I'm genuinely curious on Go and your example.
- one-more-minute 12y agoTo answer your question, no, but it's not really the key issue. The problem is storage; I can't store a value of 1.5 in my original Vector2D, so I had to reimplement it. If that sounds silly (why not just change the original Vector2D to floats?) imagine you're implementing a game, for example, and you want to store game objects in sets. You can't just write one type-safe Set structure – you have to implement Monster1Set, Monster2Set, PlayerSet, Coin1Set... Basically, any time you want to go outside of Go's built-in array and dictionary types, you run into problems.
- gnuvince 12y agoNo, what he means is the you would need to write these two functions: func DotProductInt(v1, v2 Vector2D) int { return v1.x*v2.x + v1.y*v2.y } func DotProductFloat(v1, v2 Vector2DFloat) float64 { return v1.x*v2.x + v1.y*v2.y } If Go allowed for parametric polymorphism, the type of the elements could be abstracted away like this (not real syntax obviously) type Vector2D<t> struct { x, y t } func DotProduct(v1, v2 Vector2D<t>) t { return v1.x*v2.x + v1.y*v2.y }