I have heard that it is always good to define variable type when you declare a variable but wherever I see Go code, be it any package or library or blog, I find the short way to define variables without mentioning the type.
Is not necessary to always write the type of a variable. Go has type inference with the :=
operator, but sometimes you have to declare it.
You can declare a variable in 2 ways:
var age int
age := 12
On the first one you declare a variable called age
of type int
but no value. You can set the value later or assign it right there as var age int = 12
On the second one you declare a variable called age
of type int
(because 12 is int
)
Local variables usually get assigned and declared with :=
where package variables is good to declare with var x Type