hi!.. I wanted to know the difference in the ways of assignign values to a variable
a := 42
and
var a = 42
hi!.. I wanted to know the difference in the ways of assignign values to a variable
a := 42
and
var a = 42
a := 42
mean create new variable named a
and assign value 42. a = 42
assign value 42 to an existing variable named a
. also look here to understand variable declarations.
Yes, those ways are equivalent.
a :=42 is a short form for var a = 42.
nope. first form always create a new variable.the second form assume that the variable already exist and assign a new value. the second form won’t work without explicit declaration (with := or var).
There is a var
in the second form. They are equivalent.
One difference between them is that the short form declaration is valid in a couple of places where the long form is not; for example
if foo, err := somefunc(); err != nil {
// ...
}
cannot be written as
if var foo, err = somefunc(); err != nil {
// ...
}
Of course,
var foo, err = somefunc()
if err != nil {
// ...
}
is valid but different (the scope of foo
and err
is larger).
Also, the short form allows redeclaring variables, as long something new is introduced. That is,
foo := 42
foo, bar := 43, 44
is valid, while
foo := 42
var foo, bar = 43, 44
is not.
the second form won’t work without explicit declaration (with := or var).
mean that only var a = 42
is the same with a := 42
. just a = 42
is not the same with a := 42
.
Nobody said it was.
i guess you’re right, i missed var…
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.