Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does go have := short assignments inside functions?

Tags:

go

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

like image 771
Saad Avatar asked Sep 26 '12 22:09

Saad


People also ask

What happens when you define a function inside another function?

If you define a function inside another function, then you’re creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function. This provides a mechanism for you to create helper functions, closures, and decorators.

What is assignment operator in C with example?

“=”: This is the simplest assignment operator which is used to assign the value on the right to the variable on the left. This is the basic definition of assignment operator and how does it functions. Syntax: num1 = num2; Example: a = 10; ch = 'y';

What is go statement in C++?

A "go" statement starts the execution of a function call as an independent concurrent thread of control, or goroutine , within the same address space. GoStmt = "go" Expression . The expression must be a function or method call; it cannot be parenthesized.

Which operators are used to assign values to a variable?

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value.


1 Answers

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.

like image 193
dskinner Avatar answered Sep 24 '22 12:09

dskinner