string - Unexpected value when getting value from a map -


so have struct this:

type magni struct {     ...     handlers map[string]func(*message)     ... } 

and have function create new instance of struct:

func new(nick, user, real string) *magni {     return &magni{         ...         handlers: make(map[string]func(*message)),         ...     } } 

but can't handlers map key "hey" when "hey" in variable, works if type myself. here method of struct magni , m pointer struct magni:

handler := m.handlers[cmd[3][1:]] // cmd[3][1:] contains string "hey" handler2 := m.handlers["hey"] 

for reason, value of handler nil , value of handler2 0x401310, not expecting handler nil.

am doing wrong or expected behavior?

getting value based on value of variable works:

m := map[string]string{"hey": "found"} fmt.println(m["hey"]) // found  cmd := []string{"1", "2", "3", "hey"} fmt.println(m[cmd[3]]) // found 

it works if variable of string type , slice value, e.g.:

cmd = []string{"1", "2", "3", "hhey"} fmt.println(m[cmd[3][1:]]) // found 

you issue cmd[3] string "hey" itself, if slice cmd[3][1:], cut off first character (or precise: first byte utf-8 encoding sequence, memory representation of strings, characters of "hey" map bytes one-to-one), "ey", not find associated value in map of course:

cmd = []string{"1", "2", "3", "hey"} fmt.println(m[cmd[3][1:]]) // not found (empty string - 0 value) 

try these on go playground.

if cmd[3] "hey", no need slice it, use key.

edit: claim cmd[3] contains string ":hey". if would, work:

cmd = []string{"1", "2", "3", ":hey"} fmt.println(m[cmd[3][1:]]) // found 

so cmd[3] not think is. may contain 0 bytes or unprintable characters. print bytes verify. example bytes of string ":hey" are: [58 104 101 121]

fmt.println([]byte(":hey")) // prints [58 104 101 121] 

print cmd[3] verify:

fmt.println([]byte(cmd[3])) 

you compare strings think is, tell whether equal (and won't tell difference is):

fmt.println(cmd[3] == ":hey", cmd[3][1:] == "hey") 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -