Simple assignment

The assignment statement updates the value to which a variable refers. In its simplest form, the assignment = consists of the variable to the left of the symbol and the expression to the right.

X = 1 // named variable *p = true // Indirect variable Person. name = "Tom" // Struct member count[x] = count[x] * scale // Array or slice or map elementCopy the code

Each arithmetic operator and binary operator corresponds to an assignment operator, for example:

Count [x] = count[x] * scale is equivalent to count[x] *= scaleCopy the code

The Go language is very similar to Java in this respect, in addition to repeated increments or decrement

You can also use the following operations:

 v :=1
 v++
 v--
Copy the code

Multiple assignments

In short, it allows multiple variables to be assigned together, which is more advanced than Java

X,y = 1,2 a[I],a[j] = a[j],a[I] # func GCD (x,y int) int{for y! = 0{x,y = y,x%y}} # func fib(n int) int{x,y = 0,1 for I := 0; i<n; i++{ x,y = y,x+y } return x }Copy the code

It goes without saying that the biggest benefit of multiple assignment is that it makes code look more compact and beautiful

A, b, c = 0Copy the code

If you call a function that returns multiple values, the number of values received on the left must be the same as the number of values returned by the function on the right.

 f,err = os.open("test.txt")
Copy the code

There are similar situations

V,ok = m[key] // Map query v,ok = x.(TCopy the code

Like variable declarations, you can assign unwanted values to empty identifiers:

_, err = IO. Copy (DST, SRC) / / rejected the number of bytes, and ok. = x (T) / / check types but discarded resultsCopy the code

Sex can be assigned a value

Assignment operations are divided into explicit and implicit. In practice, we mostly use explicit assignment, but there are also many cases of implicit assignment. For example, a function call implicitly assigns the value of a parameter to the corresponding parameter variable. A return statement assigns result to the result variable.

Literal expressions that conform to a type, such as slice

 medals := []string{"tom","bob","leo"}
Copy the code

Implicitly assign a value to each element, which can be written like this:

 medals[0] = "tom"
 medals[1] = "bob"
 medals[2] = "leo"
Copy the code

It is worth noting that map and channel elements follow a similar implicit assignment, although they are not ordinary variables.

Whether an assignment is implicit or explicit, if the variable on the left is of the same type as the value on the right, it is legal. In layman’s terms, assignment is only legal if the value is assignable to a variable type.

Nil can be assigned to any interface variable or reference type.