Saad
Saad

Reputation: 28486

Why does go have := short assignments inside functions?

I don't quite understand the specific purpose of short assignments,

why do this:

x:= 10

when this is also possible:

var x = 10

Is there any specific use case where short assignments are more convenient Thanks

Upvotes: 10

Views: 3224

Answers (5)

dskinner
dskinner

Reputation: 10857

if x, err := fn(); err != nil {
    // do something
}

In the above case, the variables are confined within the if statement. If you try to access err outside of the if statement, it won't be available. Likewise for x. There's various cases where maintaining scope like this might be useful, but I'd say the use of := is for given styles like the above with if, switch, for.

For some additional background, var also allows grouping, much like using import.

var (
    y = 1
    z = 2
)

which pushes the use-cases for var vs := further apart.

Upvotes: 16

Matt
Matt

Reputation: 1424

I believe that := mainly exists as a convenient syntax for receiving the results of function calls, where one often desires to reuse an existing variable, while declaring a new one:

x, err := func1()
if err != nil {
    fmt.Fatal(err)
}
y, err := func2()
if err != nil {
    fmt.Fatal(err)
}

The above code compiles because := allows existing variables to be listed, as long as at least one new variable is created. Try replacing y, err := with var y, err = and you will find it does not compile.

Upvotes: 2

RobEdouard
RobEdouard

Reputation: 101

Example 1:

var age int = 30

Example 2:

var age = 30

Example 3:

age := 30

All of the examples above are the same. Example 2 and Example 3 simply 'infer' the type. It's also a type of shorthand. Below is an excerpt from a public domain - creative commons pdf, "An Introduction To Programming In GO", by Caleb Doxsey

'Since creating a new variable with a starting value is so common Go also supports a shorter statement:

x := "Hello World"

Notice the : before the = and that no type was specified. The type is not necessary because the Go compiler is able to infer the type based on the literal value you assign the variable. (Since you are assigning a string literal, x is given the type string)

The compiler can also do inference with the var statement:

var x = "Hello World"

The same thing works for other types:

x := 5
fmt.Println(x)

Generally you should use this shorter form whenever possible.'

Upvotes: 3

OscarRyz
OscarRyz

Reputation: 199215

There is no reason in that case, they are equivalent.

It makes sense when you have this

var i int
i = 0

So you can be more concise and infer the type with

i := 0

But otherwise they're exactly the same.

Upvotes: 1

jorelli
jorelli

Reputation: 8350

x := fn()

that will make x the same type as the return type of the function fn. If you refactor your code and the return type of fn changes, x's type will be changed for free.

...and it's less typing.

Upvotes: 0

Related Questions