stan.sm
stan.sm

Reputation: 323

Make pointer from an unknown type

Is it possible to make an equivalent code to the following without mentioning a specific type (SomeStruct in this case)?

// takes SomeStruct{} and returns &SomeStruct{}
func MakePointerFromStruct(someStruct interface{}) interface{} {
    obj := someStruct.(SomeStruct)
    return interface{}(&obj)
}

I've created a playground


My actual problem is that I need to cast to &User{} some data from a session (which I get from redis and which is in a form User{}) but code which operates on that deserialized value doesn't know anything about its type and tries to cast it to an interface..

The problem is that there is one pointer method on User{} which modifies data. And to cast to an interface value in an interface{} variable must already be a pointer: &User{}

Some code to make it clear:

type User struct {}
func (u *User) FillFromOauth(name string) {
  u.Name = name
  //...
}

type UserInterface interface {
  FillFromOauth(name string)
}

func someFuncWhereCastingOccurs(userObj interface{}) {
  user := userObj.(UserInterface) // 
}

data := User{}
someFuncWhereCastingOccurs(data)

Upvotes: 0

Views: 778

Answers (3)

divan
divan

Reputation: 2807

What's the problem on just taking address of your User{} variable?

data := &User{}
someFuncWhereCastingOccurs(data)

Take a look at this example: http://play.golang.org/p/xYqfr5G4mw

PS. By the way, it's not casting, it's type assertion.

Upvotes: 1

newacct
newacct

Reputation: 122429

Something like this should work:

import "reflect"

func MakePointerFromStruct(someStruct interface{}) interface{} {
    ptrValue := reflect.New(reflect.TypeOf(someStruct))
    reflect.Indirect(ptrValue).Set(reflect.ValueOf(someStruct))
    return ptrValue.Interface()
}

Upvotes: 1

web-demolisher
web-demolisher

Reputation: 56

A pointer can be converted to the type-unsafe generic pointer by

return unsafe.Pointer(&p)

That value can then be cast to whatever pointer type you choose.

Upvotes: 0

Related Questions