Why do you have: = short jobs inside functions?

I don’t quite understand the specific purpose of short appointments,

why do this:

x:= 10 

when it is also possible:

 var x = 10 

Is there any specific use case when short appointments are more convenient Thanks

+4
source share
5 answers
 if x, err := fn(); err != nil { // do something } 

In the above case, the variables are limited inside the if statement. If you try to access err outside the if statement, it will not be available. Similarly for x . There are various cases where using such a volume can be useful, but I would say that using := for given styles, as indicated above, with if , switch , for .

For some additional background, var also allows grouping, similar to using import .

 var ( y = 1 z = 2 ) 

which further extends the use cases for var vs := .

+12
source

Example 1:

 var age int = 30 

Example 2:

 var age = 30 

Example 3:

 age := 30 

All the above examples are the same. Example 2 and Example 3 simply ' infer ' the type. It is also a type of contraction. Below is a snippet from the public domain - Creative Commons PDF, Introduction to GO Programming, Caleb Doxsey

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

 x := "Hello World" 

Note : before = and that type is not specified. A type is not needed because the Go compiler can infer a type based on the literal value that you assign to the variable. (Since you are assigning a literal string, x is given a string of type)

The compiler can also output 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 .

+2
source

In this case, there is no reason, they are equivalent.

It makes sense if you have it.

 var i int i = 0 

So you can be more concise and deduce the type with

 i := 0 

But otherwise they are exactly the same.

+1
source

I believe that := basically exists as a convenient syntax for obtaining the results of function calls, where it is often required to reuse an existing variable by 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 you to list existing variables if at least one new variable is created. Try replacing y, err := with var y, err = , and you will find that it does not compile.

+1
source
 x := fn() 

which makes x the same type as the return type of fn . If you reorganize your code and return type fn , type x will be changed for free.

... and it prints less.

0
source

Source: https://habr.com/ru/post/1436485/


All Articles