Example 1:
var age int = 30
Example 2:
var age = 30
Example 3:
age := 30
All the above examples are the same. Example 2 and Example 3 simply ' infer ' the type. It is also a type of contraction. Below is a snippet from the public domain - Creative Commons PDF, Introduction to GO Programming, Caleb Doxsey
'Since creating a new variable with a start value is so common, Go also supports a shorter statement:
x := "Hello World"
Note : before = and that type is not specified. A type is not needed because the Go compiler can infer a type based on the literal value that you assign to the variable. (Since you are assigning a literal string, x is given a string of type)
The compiler can also output with the var statement:
var x = "Hello World"
The same thing works for other types:
x := 5 fmt.Println(x)
Generally, you should use this shorter form whenever .
source share