Get pointer to interface value?

185 views
Skip to first unread message

eadfrith

unread,
Dec 21, 2009, 4:04:03 PM12/21/09
to golang-nuts

Is there a way, given a variable of interface type, of getting a
pointer to the value stored in the variable?

Given:

type Inf interface {}
type A struct {v int}

x := A{1}
ix := Inf(x)

I can use a type assertion, to get a copy of x:

y := ix.(A)

But what if I want to recover a pointer to x in order to update it? Am
I missing something or is this not possible?

BTW, I know I can do this

y.v++
ix = y

But if A is large then I might not want to incur the overhead of a
copy-by-value.

Thanks


Rob 'Commander' Pike

unread,
Dec 21, 2009, 4:10:54 PM12/21/09
to eadfrith, golang-nuts

On 22/12/2009, at 8:04 AM, eadfrith wrote:

>
> Is there a way, given a variable of interface type, of getting a
> pointer to the value stored in the variable?
>
> Given:
>
> type Inf interface {}
> type A struct {v int}
>
> x := A{1}
> ix := Inf(x)
>
> I can use a type assertion, to get a copy of x:
>
> y := ix.(A)
>
> But what if I want to recover a pointer to x in order to update it? Am
> I missing something or is this not possible?

It is not possible.

> BTW, I know I can do this
>
> y.v++
> ix = y
>
> But if A is large then I might not want to incur the overhead of a
> copy-by-value.

That's the tradeoff.

-rob


SnakE

unread,
Dec 21, 2009, 6:49:59 PM12/21/09
to eadfrith, golang-nuts
2009/12/22 eadfrith <eadf...@gmail.com>


Is there a way, given a variable of interface type, of getting a
pointer to the value stored in the variable?

Given:

type Inf interface {}
type A struct {v int}

x := A{1}
ix := Inf(x)

x is a value, so ix gets a copy of that value wrapped in interface.  They become distinct.  You cannot modify x via ix, and you cannot get to x via ix.
Reply all
Reply to author
Forward
0 new messages