Stack vs heap allocation of structs in Go, and how they relate to garbage collection

前端 未结 5 1068
谎友^
谎友^ 2020-11-30 16:19

I\'m new to Go and I\'m experiencing a bit of congitive dissonance between C-style stack-based programming where automatic variables live on the stack and allocated memory l

5条回答
  •  心在旅途
    2020-11-30 17:06

    type MyStructType struct{}
    
    func myFunction1() (*MyStructType, error) {
        var chunk *MyStructType = new(MyStructType)
        // ...
        return chunk, nil
    }
    
    func myFunction2() (*MyStructType, error) {
        var chunk MyStructType
        // ...
        return &chunk, nil
    }
    

    In both cases, current implementations of Go would allocate memory for a struct of type MyStructType on a heap and return its address. The functions are equivalent; the compiler asm source is the same.

    --- prog list "myFunction1" ---
    0000 (temp.go:9) TEXT    myFunction1+0(SB),$8-12
    0001 (temp.go:10) MOVL    $type."".MyStructType+0(SB),(SP)
    0002 (temp.go:10) CALL    ,runtime.new+0(SB)
    0003 (temp.go:10) MOVL    4(SP),BX
    0004 (temp.go:12) MOVL    BX,.noname+0(FP)
    0005 (temp.go:12) MOVL    $0,AX
    0006 (temp.go:12) LEAL    .noname+4(FP),DI
    0007 (temp.go:12) STOSL   ,
    0008 (temp.go:12) STOSL   ,
    0009 (temp.go:12) RET     ,
    
    --- prog list "myFunction2" ---
    0010 (temp.go:15) TEXT    myFunction2+0(SB),$8-12
    0011 (temp.go:16) MOVL    $type."".MyStructType+0(SB),(SP)
    0012 (temp.go:16) CALL    ,runtime.new+0(SB)
    0013 (temp.go:16) MOVL    4(SP),BX
    0014 (temp.go:18) MOVL    BX,.noname+0(FP)
    0015 (temp.go:18) MOVL    $0,AX
    0016 (temp.go:18) LEAL    .noname+4(FP),DI
    0017 (temp.go:18) STOSL   ,
    0018 (temp.go:18) STOSL   ,
    0019 (temp.go:18) RET     ,
    

    Calls

    In a function call, the function value and arguments are evaluated in the usual order. After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value back to the calling function when the function returns.

    All function and return parameters are passed by value. The return parameter value with type *MyStructType is an address.

提交回复
热议问题