← BYTES
Go·Starter·Ref: 10.1.11

When would you use `var x int` instead of `x := 0`?

Have a question about this video? Mention reference 10.1.11 when you contact us.

a.var is only valid inside loops, := works everywhere
b.var declares a constant, := declares a variable
c.There's never a reason to use var, it's purely legacy syntax that should always be avoided
d.var is required at package level (outside any function), since := is only legal inside function bodies; var is also useful when you want the zero value without picking an explicit initial value
The := short declaration is restricted to inside function bodies. At package (top) level, you must use var. var is also idiomatic when you specifically want a variable to simply start at its zero value rather than writing out an explicit initializer.

Find this on YouTube & Instagram

Every BYTES video is tagged with its reference number and topic — search any of these on YouTube or Instagram to find this one:

#BYTES#BYTES10111#Go