i int
i :=10 // outside of function / method -- hope i will be auto deducted to int.
i,j := 10, 11
I understand, it could have been just as i, j = 10, 11 but by using :=, we differentiate between general is equal to & auto type deduction, however, keyword var I think looks unnecessary, things that aren’t const qualified implicitly means they could be changed.
Moreover, why Go isn’t allowing auto type deductions like i:=10 outside of function / method body.
You can’t see it now because your current use case and logic are very simple that does not require it. If we have a struct type consisting of, say megabyte size data structure and the initialization values are not guaranteed, you want to initialize it lazily. Consider the following:
func GetData(query string) {
var data *SomeLargeDataStruct // data = nil
... do some work does not need data ... // data = nil
... some N number of cycles later ... // data = nil
... Man, that is a lot of work to process ... // data = nil
data = GetFromDatabase(query) // data = megabytes OR data = nil
if data == nil { // data = megabytes OR data = nil
return // data = nil
}
... do some work with data ... // data* = megabytes
}
As I declare early in the function that I will occupy large memory usage (counting variables), it’s clear to other developers that this function will use data that will consume large memory at some point .
Notice that I do not need to burden my program memory consumption when I’m not using data from the start and should the query fails. It only occupies the data when I query it and wanted to process with it.
Because they are specific and redundant. As in, you have your constant and variable group at your disposal?
AS @NobbZ stated, (and even by looking at it yourself), what exactly is data? a constant or variable?
Keep in mind that you can declare and initialize const inside a function although the use case is rare.
As I said, the example you see now is too simple. Once you reach memory pointer and dealing with large data structure or resources consuming functions, var early declaration makes a lot sense because you want to count your total variable usage for memory consumption optimization.
There is even an opinionated practice where a function uses beyond using 12 variables is a natural indication that the function needs to be simplified mainly because we human can track ~12 variables at a time. It’s an opinion.
Speaking of simple, it’s is also because early declaration for every simple variable is too cumbersome, that’s why Go decided to create:= keyword for such use case.
we can avoid parser getting confused with Multiplication vs Declaration without var, however placing var seems to be a simple and effective approach – sake of performance