-2

:= operator is used to initialise value and then = operator is used assign values

  var fruits := [5]string{"Apple", "Orange", "Banana", "Grape", "Plum"}

gives syntax error(syntax error: unexpected :=, expecting = go),

where as,

  var fruits = [5]string{"Apple", "Orange", "Banana", "Grape", "Plum"}

syntax works fine.


Why := is not allowed to initialise with var keyword?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • It's not about initialization vs assignment, it's about variable _declaration_. If you look at the spec, `:=` is defined as a "[short variable declaration](https://golang.org/ref/spec#Short_variable_declarations)" – JimB Apr 06 '20 at 14:43
  • 2
    Does this answer your question? [Difference between := and = operators in Go](https://stackoverflow.com/questions/17891226/difference-between-and-operators-in-go) – Eklavya Apr 06 '20 at 14:44

1 Answers1

1

Think about := as declare and assign.

From language specification:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset)  // redeclares offset
a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere
ceth
  • 44,198
  • 62
  • 180
  • 289