The parameters passed golang

Parameter passing

First, on the allocation of space variables and parameter passing, go and c are very similar, are by default allocated on the stack, memory allocation has written in memory model, not repeat them here.

Due to go in the default language allocate space on the stack, so the default parameter passing is passed by value , whether you are an array or an object , after passing function parameters in the modified variables are modified copy of the stack when the function of this variable copy also destroyed, it can not affect the original object, unless you return to this variable is then assigned to the original variable.

ps: in fact we are talking about the nature of passed by reference value is passed, the value is just passed address, so you can modify the original variable.

  1. Transmitting the basic data types

    package main
    import (
        "fmt"
    )
    func swap(a int, b int) {
        var temp int
        temp = a
        a = b
        b = temp
    }
    func main() {
        x := 5
        y := 10
        swap(x, y)
        fmt.Print(x, y)
    }
    
  2. Array type transfer

    package main
    
    import "fmt"
    
    func swap(arr [2]int){
    	arr[1],arr[0]=arr[0],arr[1]
    }
    func main() {
    	a:=[2]int{0,1}
    	swap(a)
    	fmt.Print(a)
    }
    
    

    Arrays are passed by value, the print result is [01]

  3. Pointer type transmission

    func swap(a *int,b *int){
    	*a ,*b = *b,*a
    }
    func main() {
    	a:=1
    	b:=2
    	swap(&a,&b)
    	fmt.Print(a,b)
    }
    
    

    Variable & operator obtains its address, and then passed directly modify the contents of the address, print result 21

  4. slice type transfer

    When using slice as a function of parameters, the parameters will be passed a copy of the address, the memory address is about to copy parameters underlying array slice. In this case, the operation of the slice is the operating element of the underlying array element. Usually if we operate relatively array, the array will become slice passed.

    package main
    import (
        "fmt"
    )
    func function(s1 []int) {
        s1[0] += 100
    }
    func main() {
        var a = [5]int{1, 2, 3, 4, 5}
        var s []int = a[:]
        function(s)
        fmt.Println(s[0])
    }
    
  5. Function type transmission

    Go in the language, but also functions as a data type, the function can also be used as a parameter. E.g:

    package main
    import (
        "fmt"
    )
    func function(a, b int, sum func(int, int) int) {
        fmt.Println(sum(a, b))
    }
    func sum(a, b int) int {
        return a + b
    }
    func main() {
        var a, b int = 5, 6
        f := sum
        function(a, b, f)
    }
    
Published 16 original articles · won praise 3 · Views 1350

Guess you like

Origin blog.csdn.net/weixin_40631132/article/details/105208360