I believe you are correct. At compile time, a method called through an
interface is mostly unknown, and could be changed at any time. That means
that it is not known whether the implementation that eventually is called
at runtime will perform one of the behaviours that could cause references
to "escape", such as assigning a pointer to a heap value, a global
variable, or sending it through a channel.

In this case a slice, which contains a pointer to an underlying backing
array will cause that array to escape when passed to a method of an
interface value. There's no way around it because the compiler can't be
certain, in any way, what the method will do with the pointer.
On Thursday, November 6, 2014 9:17:42 AM UTC-8, Marko Kevac wrote:


While fighting with heap allocations me and my colleague noticed that
slices sent to a method via interface value always "escape" and are being
allocated on a heap.
Here is a minimal example:

When using interface value, array escapes. When using normal type, it does
not escape:

antoxa@antoxa-suse:~/_Dev/go/src/antoxa> go build -gcflags=-m 1.go 2>&1 |
grep 'escapes'
./1.go:27: &connT literal escapes to heap
./1.go:29: []int literal escapes to heap
antoxa@antoxa-suse:~/_Dev/go/src/antoxa> go build -gcflags=-m 1.go 2>&1 |
grep 'escapes'

If you think about it for a while, it seems logical. Go compiler can't
know for sure what function will be called. So it is logical to play safe
and allocate on a heap.
Can someone please elaborate on this? Are my conclusions correct? Is there
a workaround? Casting interface type to normal type before calling method
will probably work, but can't always be used and makes mocking impossible.


You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 4 | next ›
Discussion Overview
groupgolang-nuts @
postedNov 6, '14 at 5:17p
activeNov 9, '14 at 11:23p



site design / logo © 2022 Grokbase