Store function name as JSON?

64 views
Skip to first unread message

MichaelB

unread,
Apr 29, 2020, 8:18:04 PM4/29/20
to golang-nuts
Hey Gophers,

I'm trying to store a data point as a JSON (w/struct) with a Call back function to call when the item is loaded with data

Just marshaling the struct into JSON nets a blank item.. any suggestions?

example:

type Item struct {
 name string
 callback func()
 data int
}

...

func times100(i int) {
 return i * 100
}

m := Item{
 name: "first",
 callback: times100,
 data: 10,
}

.. data is loaded later after functions run... then it should run data through m.callback(data)

after striking out I thought about switching it to a string and doing a switch.. but let me know maybe i'm just doing something wrong with the callback definition 

thanks,
MB

Reto

unread,
Apr 30, 2020, 12:58:08 AM4/30/20
to MichaelB, golang-nuts
On Wed, Apr 29, 2020 at 02:17:44PM -0700, MichaelB wrote:
> I'm trying to store a data point as a JSON (w/struct) with a Call back
> function to call when the item is loaded with data

Functions aren't serializeable to json, it's not one of the types json supports.

> Just marshaling the struct into JSON nets a blank item.. any suggestions?

> type Item struct {
> name string
> callback func()
> data int
> }

If you json.Unmarshal into the above struct it can't work.
json is an external package and hence can only work with exported symbols.
You need to capitalize your struct fields in other words.

> after striking out I thought about switching it to a string and doing a
> switch.. but let me know maybe i'm just doing something wrong with the
> callback definition
Yes, enter a string and switch on that.

Greetings,
Reto

Brian Candler

unread,
Apr 30, 2020, 4:00:07 AM4/30/20
to golang-nuts
Or initialize a map with your functions, and lookup in the map.
Reply all
Reply to author
Forward
0 new messages