2.4.2. Assignability

Assignment statements is the explicit form of the assignment, but there are many places in the program will occur implicitly the assignment of behavior: the function call will be implicitly will invoke the value of the parameter assigned to the function of variable parameters, a return statement will implicitly will return the value of operating results assigned to variables, a composite type of literal (§ 4.2) behavior also can produce an assignment. For example, the following statement:

medals := []string{"gold"."silver"."bronze"}
Copy the code

Implicitly assign to each element of slice like this:

medals[0] = "gold"
medals[1] = "silver"
medals[2] = "bronze"
Copy the code

The elements of Map and chan, while not ordinary variables, have similar implicit assignment behavior. Whether an assignment is made implicitly or explicitly, the variable on the left of the assignment statement must have the same data type as the final evaluated value on the right. To put it more bluntly, assignment statements are allowed only if the value on the right is assignable to the variable on the left. The rules of assignability have different requirements for different types, and we’ll explain what’s special about each new type. For the types we’ve discussed so far, the rules are simple: types must match exactly, and nil can be assigned to any pointer or variable that references a type. Constants (§3.6) have more flexible assignment rules because they avoid unnecessary explicit type conversions. Can I use == or! For two values? = The ability to make equality comparisons is also related to assignability: for equality comparisons of any type of value, the second value must be assignable to the variable corresponding to the first value type, and vice versa. As before, we will explain the special aspects of each new genre.