go - Copy or New instance of an interface -


i have function takes interface , returns interface. initialize result copy of source, make changes, , return result. example:

playground

type interface {     copysomething()  // i'd rid of     setx(x int) }  type realthing struct {     x int }  func (t *realthing) setx(x int) {     t.x = x }  func (t *realthing) copysomething() {     newt := *t     return &newt }  func updated(original something, newx int) {     newthing := original.copysomething()  // i'd make copy without .copysomething()     newthing.setx(newx)     return newthing }  func main() {     := &realthing{x: 1}     b := updated(a, 5)     fmt.printf("a = %v\n", a)     fmt.printf("b = %v\n", b) } 

this works, copysomething() method seems unnecessary (and i'd need identical method every interface needs copy things). there better way make copy of original inside of updated() without method? there more idiomatic way achieve this?

in specific case i'm working on, away instantiating new instance of same type original (i don't need copy). problem simpler way?


based on evan's comment, thought i'd give of other reflect-based things i've tried:

newthing := reflect.new(reflect.typeof(original)) 

==> compile error: type reflect.value has no field or method setx

newthing := reflect.new(reflect.typeof(original)).interface().(something) 

===> runtime error: interface conversion: **main.realthing not main.something

newthing := reflect.indirect(reflect.new(reflect.typeof(original))).interface().(something) 

===> runtime error: invalid memory address or nil pointer dereference

at point, felt reflect becoming silly , stopped whacking @ it.

since need instantiate new instance can use reflection type of object stored in interface , instantiate copy way. reflect.new(reflect.typeof(x)) though may have play reflect.indirect() in order allocate new value , not new pointer.

it's documented here: http://golang.org/pkg/reflect/

and runnable version: http://play.golang.org/p/z8vpzdkrsk


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -