Does a local array slice return in a Go function safely?

What happens if I return a piece of an array that is a local variable of a function or method? Does Go copy array data to slice with make()? Will the capacity match the size of the slice or the size of the array?

func foo() []uint64 {
    var tmp [100]uint64
    end := 0
    ...
    for ... {
        ...
        tmp[end] = uint64(...)
        end++
        ...
    }
    ... 
    return tmp[:end]
} 
+4
source share
3 answers

This is described in detail in Spec: slice expressions .

, , . Go , Go , , , (, , , ), , .

: tmp[:end] tmp[0:end] ( low ). , len(tmp) - 0, len(tmp), 100.

, , :

a[low : high : max]

max - low.

:

var a [100]int

s := a[:]
fmt.Println(len(s), cap(s)) // 100 100
s = a[:50]
fmt.Println(len(s), cap(s)) // 50 100
s = a[10:50]
fmt.Println(len(s), cap(s)) // 40 90
s = a[10:]
fmt.Println(len(s), cap(s)) // 90 90

s = a[0:50:70]
fmt.Println(len(s), cap(s)) // 50 70
s = a[10:50:70]
fmt.Println(len(s), cap(s)) // 40 60
s = a[:50:70]
fmt.Println(len(s), cap(s)) // 50 70

Go Playground.

, - , ( ). , , .

( , , ), :

func foo(tmp *[100]uint64) []uint64 {
    // ...
    return tmp[:end]
}

( ), "" "" :

func main() {
    var tmp [100]uint64
    foo(&tmp)
}

go run -gcflags '-m -l' play.go, :

./play.go:8: leaking param: tmp to result ~r1 level=0
./play.go:5: main &tmp does not escape

tmp .

, [100]uint64 , . . "" . Go ?

+3

.

Go , , .

.

+2

. .

, , . , " ".

+1

Source: https://habr.com/ru/post/1671136/


All Articles