The original
tour.golang.org/basics/4
tour.golang.org/basics/5
tour.golang.org/basics/6
tour.golang.org/basics/7
The translation
A function can have zero or more arguments. In this case, the add method takes two parameters of type int
Note: The type comes after the variable name
See article on Go’s Declaration syntax for why arguments look the way they do.
The sample
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
Copy the code
When two or more consecutive named parameters share the same type, the type can be omitted except for the last parameter
package main
import "fmt"
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
Copy the code
Functions can return any number of values, and swap returns two strings
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Copy the code
Namable return value Go Return value can be named. If named, the two named variables are declared at the beginning of the function. These names can be used to document the meaning of the return value. A return statement with no arguments returns the named return value, which is known as a “naked” return.
“Naked” return statements should only be used in shorter functions, as shown in the example. They can seriously affect the readability of a program.
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
Copy the code