Have a map of string vs function (pointer)

1,355 views
Skip to first unread message

ashani

unread,
Feb 12, 2011, 11:46:11 PM2/12/11
to golang-nuts
Hi,

I am new to go..I want a map of strings vs functions.
I looked up the documentation but could not find any.
I tried many ways but am always getting an error in the declaration of
the map.

Something like:

func f1(int) int {
...
}

func f2 (int) int {
...
}

map [string] func(int) (int)

and want to initialize with :
"1"=>f1
"2"=>f2

How can I do this ?

Thanks in advance

jimmy frasche

unread,
Feb 12, 2011, 11:51:08 PM2/12/11
to ashani, golang-nuts
var str2fn = map[string]func(int)int{
"1": f1,
"2": f2, //required because of semicolon insertion

Ostsol

unread,
Feb 12, 2011, 11:52:35 PM2/12/11
to golang-nuts
What exactly does your code look like and what kind of error are you
getting?

The following works for me:

a := make(map[string]func(int)(int))
a["1"] = f1
a["2"] = f2

Or:

a := map[string]func(int)(int){"1": f1, "2": f2}

-Daniel

ashani

unread,
Feb 13, 2011, 12:15:39 AM2/13/11
to golang-nuts
Thanks for you help !
It is now compiling after I added the last "," ...

my actual code snippet is:

.......

func execQuit (conn net.Conn, req string ) (os.Error, string) {
var resp string
err := sendCtrlCmd(conn, "QUIT");
if err == nil {
err, _, resp = recvCtrlResp(conn)
}
return err, resp
}

func execPass (conn net.Conn, cmd string) (os.Error, string) {
var resp string
err := sendCtrlCmd(conn, "PASS " + cmd)
if err == nil {
err, _, resp = recvCtrlResp(conn)
}
return err, resp
}

func execUser (conn net.Conn, cmd string) (os.Error, string) {
var resp string
err := sendCtrlCmd(conn, "USER " + cmd)
if err == nil {
err, _, resp = recvCtrlResp(conn)
}
return err, resp
}


var commandTable = map [string] func(net.Conn, string ) (os.Error,
string) {
"QUIT" : execQuit,
"PASS" : execPass,
"USER" : execUser,
}
....
Reply all
Reply to author
Forward
0 new messages