On Sat, Mar 11, 2017 at 10:14 PM, priyank pulumati <pulumati.priy...@gmail.com> wrote: > Hello, > Go newbie here > > func (data map[string] interface {}) { > if len(data) == 0 { > data := make(map[string]interface{}) > data["user"], _ = store.GetUser(context.Get(req, "userid").(string)) > } else { > data["user"], _ = store.GetUser(context.Get(req, "userid").(string)) > } > log.Println(data["user"]) > }
Go has 'block scoping' where variables can be declared to be valid within a block (usually between two curly braces {} ) Variables in inner blocks can have the same names as variables in outer blocks but still be different variables. This is called 'shadowing'. In your above code you have a variable called 'data' declared at the scope of the function. You then declare a new variable also called 'data' within the true block of the if. These are different variables even through they have the same name. When you log.Println(data["user"]) at the end you're referring to the variable 'data' declared in the function scope and not the variable called 'data' that you declared in the scope of the if block. You probably want to use '=' instead of ':=' so you're assigning a value to the existing variable and not declaring a new one. Note that assigning a value to the function scoped variable 'data' won't modify the value you passed in. So if you're creating a new map value you'll need to return it to the caller. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.