Dynamically instantiating types

1,221 views
Skip to first unread message

tomwilde

unread,
Mar 21, 2012, 1:23:11 PM3/21/12
to golan...@googlegroups.com
Is there a way to reference a user-defined type and then instantiate this type dynamically in Go?

An example could be:

    type MyType struct {
        Name  string
        Active bool
    }

    func (m *MyType) SetName(n string) {
        m.Name = n
    }

1.- How could I store a reference to this type?

2.- How can I create instances of this type by using the reference?

Brad Fitzpatrick

unread,
Mar 21, 2012, 1:33:24 PM3/21/12
to tomwilde, golan...@googlegroups.com

chris dollin

unread,
Mar 21, 2012, 1:36:33 PM3/21/12
to tomwilde, golan...@googlegroups.com
On 21 March 2012 17:23, tomwilde <sedevel...@gmail.com> wrote:
> Is there a way to reference a user-defined type and then instantiate this
> type dynamically in Go?

> 1.- How could I store a reference to this type?


>
> 2.- How can I create instances of this type by using the reference?

Brad suggests considering reflection, but another way to do something
that might be like what you want is to use functions -- you can write a
make-me function for the type and pass that around and call it when
you need to generate a value

func makeMyType() interface{} { return MyType{...} }

Chris

--
Chris "allusive" Dollin

Message has been deleted

tomwilde

unread,
Mar 21, 2012, 5:50:42 PM3/21/12
to golan...@googlegroups.com
Thank you very much Peter. I was able to continue coding with your example.


Am Mittwoch, 21. März 2012 18:36:50 UTC+1 schrieb Peter Thrun:
Is there a way to reference a user-defined type and then instantiate this type dynamically in Go?

http://play.golang.org/p/tgXdmlQR97

Reply all
Reply to author
Forward
0 new messages