Which example is better (if ok :=expression; ok)

Hello all,

   body, err := record.MarshalToString()
   if err != nil {
      return err
   }

Versus:

var err error
var body string

if body, err = record.MarshalToString(); err != nil {
	return err
}

I cannot tell which one I should be using, as I keep seeing both versions in the same repo.

The second doesn’t really provide any benefit. Doing the call and test together in the if is useful to limit the scope of the err variable. I follow the first pattern in this situation.

1 Like

Personally I perfer the second approach, if and only if, I can use := and keep the scope of variables extremely limited.

4 Likes

first is far more readable.

If you don’t know follow this simple rule:
If you are initializing an identifier to its zero value use var.

If you want to initialize a value to an identifier other than the zero value use :=

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.