The real gotcha is this though,

var x int
if blah {
   x,err := somefunc()
}

Probably does not do what you think as the value from somefunc() will not be 
available outside of the if statement...

This is a poor design choice by golang IMO but it is what it is...

> On Sep 4, 2018, at 9:22 AM, Nate Finch <nate.fi...@gmail.com> wrote:
> 
> Others covered this, but let me try to explain.  In Go, plain = just assigns 
> to an already existing variable
> 
> var x bool  // declares a variable, it starts with the zero value for the type
> x = true  // assigns a value to the variable
> y := true  // declares the variable and assigns it a value
> 
> Now, the tricky thing is when you have two values being assigned/declared, 
> like foo, err := bar().  In this case, as long as either or both variables 
> hasn't been declared, then := will declare one or both, and assign to one 
> that's already declared.  This makes it easier to do long lists of calls that 
> return an error, without having to use err1, err2, etc.  But it does kind of 
> muddy the waters for when to use = and when to use :=.
> 
> := has to always make at least one new variable.  = always just copies a 
> value to an existing variable or struct field.  So, like, you can't ever use 
> := to put something in a struct field (s.foo := bar will never work).
> 
> You'll get the hang of it.  You'll use := most of the time, and only = for 
> spots where the stuff on the left hand side is already declared. 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to