This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Short variable declaration :=
The answer to warm up
What are the results of the next two programs?
func main(a) {
i := 0
i, j := 1.2
fmt.Printf("i = %d, j = %d", i, j)
}
Copy the code
func main(a) {
i, j := 0.0
if true {
j, k := 1.1
fmt.Printf("j = %d, k = %d\n", j, k)
}
fmt.Printf("i = %d, j = %d\n", i, j)
}
Copy the code
- Why does the following program fail to compile
func test(i int) {
i := 0
fmt.Println(i)
}
Copy the code
The answer:
i = 1, j = 2
j = 1, k = 1
i = 0, j = 0
The parameter has already declared the variable I. Redeclarations using := are not allowed.
Multivariable assignments may be redeclared
Multiple variables can be declared at once using :=, for example:
i, j := 0.0
j, k := 1.1
Copy the code
- when
: =
When a new variable exists on the left (for example, k), the already declared variable (for example, j) is redeclared. This doesn’t introduce new variables, it just changes the values of the variables. - when
: =
No new variable compiling error on the left.
Cannot be used outside a function
: =
This short variable declaration can only be used in functions, not to initialize global variables.- Can be interpreted as
: =
It is split into two statements, declaration and assignment. Assignment statements cannot appear outside a function.
Variable parameter…
- The variable argument must be last in the function argument list (otherwise it will cause compile-time ambiguity);
- Variables are parsed inside functions as slices;
- Variable parameters can be left unfilled, otherwise the function is treated as nil slices internally;
- Variable parameters can be filled in slices;
- Mutable arguments must be of the same type (interface{} type if different);
Such as:
func sum(a int, vals...int) int {
total := a
for _, val := range vals {
total += val
}
return total
}
Copy the code
Not by value
fmt.Println(sum(1)) / / "1"
Copy the code
Passing multiple parameters
fmt.Println(sum(1.2.3.4.5)) 15 "/ /"
Copy the code
Transfer section
The parameter section needs to use slice… To represent slices, for example
values := []int{1.2.3.4.5}
fmt.Println(sum(1, values...) )/ / "16"
Copy the code