In Go,
variables
are explicitly declared and used by
the compiler to e.g. check type-correctness of function
calls.
packagemain
import"fmt"
funcmain(){
var
declares 1 or more variables.
vara="initial"fmt.Println(a)
You can declare multiple variables at once.
varb,cint=1,2fmt.Println(b,c)
Go will infer the type of initialized variables.
vard=truefmt.Println(d)
Variables declared without a corresponding
initialization are
zero-valued
. For example, the
zero value for an
int
is
0
.
vareintfmt.Println(e)
The
:=
syntax is shorthand for declaring and
initializing a variable, e.g. for
var f string = "apple"
in this case.
This syntax is only available inside functions.