Interfaces already contain a pointer to a value, and I in my case it's a struct, and I need to get a struct pointer out of an interface{}.
The use case is with sync.Map, where I put a struct containing a lock into the map, and with the Load() method I can read an interface{} value. I want to get the pointer to the original struct, so I don't copy the lock.
The alternative is to add a pointer to the struct to the Map instead, then read it back and cast the interface{} to the struct pointer, but I'm curious if the first case can be achieved.
You can't do that. If you "wrap" a non-pointer value in an interface, you can only get a non-pointer value out of it, using either a type assertion or a type switch. And since type assertion expressions are not addressable, you can't get the address of the "value" wrapped in the interface.
If you only have a value wrapped in an interface, you won't be able to get a pointer to the original value that was wrapped in the interface. Why? Because the value wrapped in the interface may only be a copy, completely detached from the original. See examples and explanation here: How can a slice contain itself?
Note that under the hood the value actually wrapped may or may not be a pointer (depending on the value's size) even if you wrapped a non-pointer value, but this is implementation detail and is hidden from you. When you extract the value, you will of course get a non-pointer.
Related
I can use methods like Text() on a big.Int and it works fine, but if I return a big.Int then use "myfunc().Text()" throws an error, whereas if I return a *big.Int, I get no error. Why can I use Text() on a big.Int, *big.Int, and on a function that returns *big.Int but not on a function whose return value is big.Int?
https://play.golang.org/p/ovgeQDHFstP
Based on this and other behavior (such as how it prints), it seems like *big.Int is the type that is intended for use, is that correct?
Also, if I make and use a variable of type big.Int or *big.Int, it is passed by reference. That's fine. But if I wanted to pass one by value, how is that best done?
Should I make a new big.Int and set it to the original value using Set() and pass that? Or should I pass the original big.Int in, and copy its value to a new big.Int using Set() inside the function? Or is there some other, better way of doing it?
The Text() method is defined for receiver type *big.Int, so obviously you can call it on variables of that type and on return values of functions returning *big.Int. You can also call it on variables of type big.Int, because Go automatically takes the address of a variable when you're trying to call its pointer methods, just to save you the trouble of typing an extra ampersand.
However you can't call it on return value of a function returning big.Int, because that value is not addressable. Here's what the spec says about addressability:
For an operand x of type T, the address operation &x generates a
pointer of type *T to x. The operand must be addressable, that is,
either a variable, pointer indirection, or slice indexing operation;
or a field selector of an addressable struct operand; or an array
indexing operation of an addressable array. As an exception to the
addressability requirement, x may also be a (possibly parenthesized)
composite literal.
Your return value is none of those things, so you can't use the pointer method any more than you can write foo := &myFunc(). To work around this, you could save the return value on a variable to make it addressable. But most likely your function should return a pointer in the first place.
Also note that there are no references in Go. Everything is passed by value, and pointers are values just like any other.
https://golang.org/pkg/math/big/ the Text() method has a pointer receiver, which means that you can only call a.Text() if a is *big.Int.
*big.Int is a pointer to big.Int, see https://play.golang.org/p/dD70b0tPeGp for a fixed version of your code
I have the following function:
func bytesToData(data interface{}, b []byte) error {
buf := bytes.NewBuffer(b)
dec := gob.NewDecoder(buf)
return dec.Decode(data)
}
I use this for getting struct data in and out of boltdb. What I'd like to do, is change that signature to:
func bytesToData(data *interface{}, b []byte) error
And then I'd like to be able to call it like this (b in this case is a gob-encoded Account)
acc := &Account{}
err := bytesToData(acc, b)
But when I do that, I get an error like Cannot use *Account for type *interface{}.
For now, I've just changed it back to interface{}. But then, if I pass in an Account or some other type directly without making it a pointer, gob throws an error. It seems like this should be checkable at compile time. And given that an argument of type interface{} accepts anything, why doesn't an argument of type *interface{} accept a pointer to anything?
The genericity of interface types in Go is not passed on to derived types. This applies to pointers (as you noticed), and also to slices, channels, etc. For example, you can't assign a []string to a []interface{}.
There are various ways to explain this. For a Haskell programmer:
Go does not have covariant or contravariant types. All type constructors (such as the * that creates a pointer type) are invariant. So even though Account and *Account (and all other types) are subtypes of interface{}, nothing is a subtype of *interface{} or []interface{}. This is sometimes inconvenient, but it keeps Go's type system and assignability rules much simpler.
For a C programmer:
An interface{} can hold a value of any type, but it does not hold it directly. Rather than being a variable-sized magic container, it is just a struct consisting of a pointer to a type and a pointer to a value. When you assign a concrete type to an interface{}, both of these fields are filled in. *interface{} is a pointer to one of these structs. When you try to assign a *Account to a *interface{}, there is nowhere to put the type information, because the *interface{} is a single machine word that just holds a pointer. So the compiler won't let you do that.
interface{} could also contain a pointer with no problem.
But there is nothing like a pointer to interface{}
See these:
Cast a struct pointer to interface pointer in Golang
Why can't I assign a *Struct to an *Interface?
I receive an interface which is basically a slice. Now I want to convert it to a pointer to the slice. The problem is, that I have either the slice itself or a Pointer to an interface.
I can easily show in a code example:
func main(){
model := []int{1,2,3,4,5,6,7,8,10,11,133123123123}
method(model)
}
func method(model interface{}){
fmt.Println(reflect.TypeOf(model)) // this is of type []int
fmt.Println(reflect.TypeOf(&model)) // this is of type *interface{}
}
What I need is this type:
fmt.Println(reflect.TypeOf(result)) // this should be type *[]int
I know the type only on runtime, therefore I cannot just take
&(model.([]int))
Is there a way using golang reflection to receive this? the type 'int' is here actually not important, important is, that it is a Pointer to a slice. *[]interface{} would be okay either.
Edit:
To make the question more clear, I should have added: I am not interested in the data of the slice, but only in getting a pointer to a slice of same type (which can basically be empty). Therefore James Henstridge answers works perfectly.
Before trying to answer the question, it is worth stepping back and asking what the *[]int value you're after should point at?
Given the way method is called we can't possibly get a pointer to the model variable from the calling context, since it will only receive a copy of the slice as its argument (note that this is a copy of the slice header: the backing array is shared).
We also can't get a pointer to the copy passed as an argument since it is stored as an interface{} variable: the interface variable owns the memory used to store its dynamic value, and is free to reuse it when the a new value is assigned to it. If you could take a pointer to the dynamic value, this would break type safety if a different type is assigned.
We can obtain a *[]int pointer if we make a third copy of the slice, but it isn't clear whether that's what you'd necessarily want either:
v := reflect.New(reflect.TypeOf(model))
v.Elem().Set(reflect.ValueOf(model))
result := v.Interface()
This is essentially a type agnostic way of writing the following:
v := new([]int)
*v = model
var result interface{} = v
Now if you really wanted a pointer to the slice variable in the calling context, you will need to ensure that method is called with a pointer to the slice instead and act accordingly.
How do I take the address of a value inside an interface?
I have an struct stored in an interface, in a list.List element:
import "container/list"
type retry struct{}
p := &el.Value.(retry)
But I get this:
cannot take the address of el.Value.(retry)
What's going on? Since the struct is stored in the interface, why can't I get a pointer to it?
To understand why this isn't possible, it is helpful to think about what an interface variable actually is. An interface value takes up two words, with the first describing the type of the contained value, and the second either (a) holding the contained value (if it fits within the word) or (b) a pointer to storage for the value (if the value does not fit within a word).
The important things to note are that (1) the contained value belongs to the interface variable, and (2) the storage for that value may be reused when a new value is assigned to the variable. Knowing that, consider the following code:
var v interface{}
v = int(42)
p := GetPointerToInterfaceValue(&v) // a pointer to an integer holding 42
v = &SomeStruct{...}
Now the storage for the integer has been reused to hold a pointer, and *p is now an integer representation of that pointer. You can see how this has the capacity to break the type system, so Go doesn't provide a way to do this (outside of using the unsafe package).
If you need a pointer to the structs you're storing in a list, then one option would be to store pointers to the structs in the list rather than struct values directly. Alternatively, you could pass *list.Element values as references to the contained structures.
A type assertion is an expression that results in two values. Taking the address in this case would be ambiguous.
p, ok := el.Value.(retry)
if ok {
// type assertion successful
// now we can take the address
q := &p
}
From the comments:
Note that this is a pointer to a copy of the value rather than a pointer to the value itself.
— James Henstridge
The solution to the problem is therefore simple; store a pointer in the interface, not a value.
Get pointer to interface value?
Is there a way, given a variable of interface type, of getting a
pointer to the value stored in the variable?
It is not possible.
Rob Pike
Interface values are not necessarily addressable. For example,
package main
import "fmt"
func main() {
var i interface{}
i = 42
// cannot take the address of i.(int)
j := &i.(int)
fmt.Println(i, j)
}
Address operators
For an operand x of type T, the address operation &x generates a
pointer of type *T to x. The operand must be addressable, that is,
either a variable, pointer indirection, or slice indexing operation;
or a field selector of an addressable struct operand; or an array
indexing operation of an addressable array. As an exception to the
addressability requirement, x may also be a composite literal.
References:
Interface types
Type assertions
Go Data Structures: Interfaces
Go Interfaces
In the first approximation: You cannot do that. Even if you could, p itself would the have to have type interface{} and would not be too helpful - you cannot directly dereference it then.
The obligatory question is: What problem are you trying to solve?
And last but not least: Interfaces define behavior not structure. Using the interface's underlying implementing type directly in general breaks the interface contract, although there might be non general legitimate cases for it. But those are already served, for a finite set of statically known types, by the type switch statement.
I just started diving into Go recently and I have one major point of confusion: I am struggling to understand when exactly it is necessary to dereference a pointer explicitly.
For example I know that the . operator will handle dereferencing a pointer
ptr := new(SomeStruct)
ptr.Field = "foo" //Automatically dereferences
In what other scenarios does go do this? It seems to for example, with arrays.
ptr := new([5][5]int)
ptr[0][0] = 1
I have been unable to find this in the spec, the section for pointers is very short and doesn't even touch dereferencing. Any clarification of the rules for dereferencing go's pointers would be great!
The selector expression (e.g. x.f) does that:
Selectors automatically dereference pointers to structs. If x is a pointer to a struct,
x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is
shorthand for (*(*x).y).z, and so on. If x contains an anonymous field of type *A, where
A is also a struct type, x.f is a shortcut for (*x.A).f.
The definition of the index expressions specifies that an array pointer may be indexed:
For a of pointer to array type:
a[x] is shorthand for (*a)[x]