DEV Community

loading...

Discussion on: Variable Declarations in Go

Collapse
beta profile image
Beta

For me I prefer var over :=, as using var explicitly indicates that a new variable is being declared. I use := under only three conditions:

  • When declaring a temporary variable inside a if- or for-clause. For example, if x := foo(); x { ... } and for i := 0; i < n; i++ { ... }.
  • When declaring a new variable to receive the returned value from a function, which returns more than one value. For example, when err has been declared before, I use x, err := foo() instead of var x bar; x, err = foo().
  • When shadowing a variable from the outer scope.
Collapse
forstmeier profile image
John Forstmeier Author

I like the approach coming from the other perspective of var being preferred. And I personally think what you've got listed here actually makes a lot of sense basically treating := as an exception to the rule of var.