【Go】function

go function

Function declaration

1
2
3
4
5
6
7
func add(x int, y int) int {
    return x + y
}

func get() int {
    return 5
}

Functions can take no parameters or accept multiple parameters. Take a closer look at the example above.

parameters

1
2
3
func add(x, y, z int) int {
    return x + y + z
}

When a function has multiple formal parameters of the same type, all but the last parameter can be omitted

return value

1
2
3
func swap(x, y int) (int, int) {
    return y, x
}

The function return value is written between the parameter and the opening brace {, allowing multiple return values to be returned

Or the function return value can also be named

1
2
3
4
5
func split(sum int) (x, y int) {
    x = sum-9
    y = sum + 9
    return
}

The function has two named return values x and y. Although the return value is not written, the function returns the named return value x y directly.

This syntax for naming return values is recommended for short functions

Persist in original technology sharing, your support will encourage me to continue to create!