A confusion on the cgo document.

96 views
Skip to first unread message

T L

unread,
Sep 30, 2019, 4:00:53 AM9/30/19
to golang-nuts

When passing a pointer to a field in a struct, the Go memory in question is the memory occupied by the field, not the entire struct. When passing a pointer to an element in an array or slice, the Go memory in question is the entire array or the entire backing array of the slice.

Why do structs and arrays have this difference?

Ian Lance Taylor

unread,
Sep 30, 2019, 9:10:28 PM9/30/19
to T L, golang-nuts
Because it's normal to call a C function with (&a[0], len(a)) to let
the C function examine all elements of the array or slice. It's not
normal to call a C function with (&s.f) and expect the C function to
examine all elements of the struct; if the C function wants to examine
all elements of a struct, you would pass &s, not &s.f. But you don't
want to pass &a to a C function; with the way C pointers work, you
want to pass a pointer to an element, not a pointer to the array or
slice. (Admittedly passing a pointer to an array would work anyhow,
but passing a pointer to a slice would not.)

Ian

T L

unread,
Oct 2, 2019, 4:36:52 AM10/2/19
to Ian Lance Taylor, golang-nuts
Got it. Thanks, Ian.
Reply all
Reply to author
Forward
0 new messages