Godot Version
Any
Question
A lot of the tutorials and videos I’ve been following to learn Godot define variables this way. But from my understanding it’s always best to strictly type your variables.
For example, they do this:
var some_array: = []
instead of:
var some_array: Array = []
All the documentation says is “Godot will try to infer types if you write a colon, but you omit the type”, but isn’t that what Godot does when you don’t use a colon at all? And wouldn’t it still be slower performance-wise than hard defining the type, as Godot still has to do the extra work of inferring?
I personally try to statically type all my vars to make it clear and minimize errors, but it’s a trend I see a lot and still not sure why.
The inference happens at compile time, not at runtime, and the right side of the assignment must have an unambiguously defined type. Otherwise := assignment will report an error and the script won’t be compiled. Initializing with := is in fact exactly the same as statically declaring the type. It’s just a shorthand.
2 Likes
I see. In that case, why do we use a colon at all? Can it not just be var some_array = []? Or is it that without a colon it does the inference on the fly during runtime?
Without the colon it’s just a regular assignment and the variable remains untyped.
var some_array = []
some_array = 10 # fine
But:
var some_array := []
some_array = 10 # "Cannot assign..." error
Inference only makes sense at compilation time. At runtime all types are known. Inference is not type casting. The whole purpose of static typing is to transfer potential type mismatch errors from runtime to compile time and catch them early, before the code is even run.
2 Likes
Ah, that makes a lot more sense. Guess I didn’t really connect the dots in my head around compile time vs runtime and how variables are defined during actual execution. Thanks for breaking it down.
The documentation could do with a bit more detail on this, and yeah in the tutorials they don’t explain why they do it, they just do it, so it’s been a question on my mind for a while now.