Golang: functions

  • 2020-05-27 05:50:02
  • OfStack

function

The core design in the Go language is declared by the keyword func


func funcName(input type1, input2 type2) (output1 type1, output2 type2) {
    //logical code
    return value1, value2
}

The basic grammar

1. Grammar


//1 A function
func func_name(a int) {
    println(a)
} // Multiple parameters, no return value
func func_name(a, b int, c string) {
    println(a, b, c)
} // Single return value
func func_name(a, b int) int { // Same type, can be omitted   a, b int
    return a + b
} // Multiple return values
func func_name(a, b int) (c int, err error) {  // The return value can also be    (int, error)
    return a+b, nil
} func SumAndProduct(A, B int) (int, int) {
    return A+B, A*B
}

2. Specification:

The keyword func The statement
There can be a 1 Two or more parameters, each followed by a type , through "," The separator function can return multiple values
Return value declaration. You can declare only types
    If there is no return value, you can omit the last return information
    If there is a return value, it must be added on the outer layer return
Go Nested functions are not supported (nested), Overloading ( overload ) and default parameters (default parameters)
Support:
    1. No need to declare the prototype
    2. Variable length variable parameters
    3. The return value more
    4. Name the return value parameter
    5. Anonymous functions
    6. closure Note:
    Function USES func At the beginning, you can't have the open curly brace 1 line

Functions that start with a lowercase letter are visible in the package, and functions that start with an uppercase letter can only be called by other packages


Multiple return values and named return parameters

You can return multiple results like python, but not tuple

For unwanted return values, you can throw the garbage can _

If you use a named return parameter, the return statement can be empty. return is not null, and the order of return values is the order of return rather than the order declared in the function header


package main func change(a, b int) (x, y int) {
    x = a + 100
    y = b + 100     return   //101, 102
    //return x, y  // Same as above
    //return y, x  //102, 101
} func main(){
    a := 1
    b := 2
    c, d := change(a, b)
    println(c, d)

If the named return parameter is overridden by a variable of the same name in the code block, you must use explicit return to return the result

There is no need to force the name of the return value, but the named return value makes the code cleaner and more readable

Parameter passing: pass value and pass pointer

Pointer, Go keep pointer, use "." instead of "- > "Action pointer target object member operator


& Fetch variable address
* Indirectly access the target function through a pointer func add1(a int) int {
    a = a + 1
    return a
} x := 3
x1 := add1(x)
x //3
x1 //4
By value, x1 The value of func add2(a *int) int {
    *a = *a + 1
    return *a
}
x := 3
x1 := add2(&x)
x // 4
x1 // 4

Multiple functions can operate on the same object

Pass pointer is relatively lightweight (8byte), just pass memory address, we can use the pointer to pass bulk structure

In the Go language, string,slice,map are implemented in a similar way, so they can be passed directly without having to fetch the address and then pass the pointer

Note that if the function needs to change the slice length, it still needs to fetch the address pass pointer

Parameter passing: variable parameter

The variable parameter is essentially 1 slice and must be the last parameter

When passing slice to an argument function, be careful to use... Otherwise, it will be treated as a single parameter of dang, similar to python


package main func sum(s string, args ...int)  {
    var x int
    for _, n := range args {
        x += n
    }
    println(s, x)
}
func main(){
   sum("1+2+3=", 1, 2, 3)    x := []int{0,1,2,3,4}
   sum("0+1+2+3=", x[:4]...)
} ...type A type can only exist as an argument type to a function, and last 1 A parameter
Essentially, 1 Array slices, namely []type

An indefinite parameter of any type


func Printf(format string, args ...interface{}) {
}

Anonymous functions

f := func(x,y int) int {
    return x + y
}

Functions as values and types

In Go, the function is also a variable, which can be defined by type, and its type is all the same parameters, the same return value

grammar


type typeName func (input1 inputType1, input2 inputType2 [, ....]) (result1 resultType1 [,....])

Usage e. g. 1


type testInt func(int) bool // The statement 1 Function types func filter(slice []int, f testInt) []int {
    var result []int
    for _, value := range slice {
        if f(value) {
            result = append(result, value)
        }
    }
} func isOdd(integer int) bool {
    if integer % 2 == 0 {
        return false
    }
    return true
} filter(a, isOdd)

This is useful when writing interfaces

Usage e. g. 2

You can define a function type or pass it as a value (the default is nil)


//1 A function
func func_name(a int) {
    println(a)
} // Multiple parameters, no return value
func func_name(a, b int, c string) {
    println(a, b, c)
} // Single return value
func func_name(a, b int) int { // Same type, can be omitted   a, b int
    return a + b
} // Multiple return values
func func_name(a, b int) (c int, err error) {  // The return value can also be    (int, error)
    return a+b, nil
} func SumAndProduct(A, B int) (int, int) {
    return A+B, A*B
}
0
Results:

hello world
3


Related articles: