This is a creation in
Article, where the information may have evolved or changed.
3. Toad notes Go language-functions
Function
A function can have no arguments or accept multiple arguments.
Add accepts two parameters of type int .
Code
Package Main
Import "FMT"
Func Add (x int, y int) int {
Returnx + y
}
Func Main () {
Fmt. Println (Add (42,13))
}
Execution Result:
55
When two or more consecutive function named arguments are of the same type, they can be omitted except for the last type.
In this case,
x int, y int
Be abbreviated as
x, y int
Multi-value return
The function can return any number of return values.
The swap function returns two strings.
For example:
Package Main
Import "FMT"
Func swap (x, y String) (string, string) {
Returny, X
}
Func Main () {
A, B: =swap ("Hello", "World")
Fmt. Println (A, B)
}
Perform:
World Hello
Named return value
The return value of Go can be named and used as a variable.
The name of the return value should have some meaning and can be used as a document.
A return statement with no arguments returns the current value of the result. Which means ' direct ' return.
The direct return statement should only be used in short functions such as the following. In long functions, they can affect the readability of the code.
The code is as follows:
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))
}
Execution Result:
7 10