Questions about Maps


(Cherolyn Lexvold) #1

For a hands on exercise, I was given the following instructions:

Create a map with a key of TYPE string which is a person’s “last_first” name, and a value of TYPE []string which stores their favorite things. Store three records in your map. Print out all of the values, along with their index position in the slice.
bond_james, Shaken, not stirred, Martinis, Women
moneypenny_miss, James Bond, Literature, Computer Science
no_dr, Being evil, Ice cream, Sunsets

This is what I came up with:
https://play.golang.org/p/wk3fziQomX5

What did I do wrong?


(Cherolyn Lexvold) #2

After listening to the teacher’s video, I got
https://play.golang.org/p/nkz9O0Q6Lg7

So I think I’m good. I just need to study this a little more.


(Jay Ts) #3

It looks good so far. You just need to add the part that prints the indices and values of the slices.


(Cherolyn Lexvold) #4

You just need to add the part that prints the indices and values of the slice

What’s wrong here: https://play.golang.org/p/bfCtHrqFZMx


(Norbert Melzer) #5

The missing dot (.) between fmt and Println.

Reading error messages might help to solve those problems.


(Cherolyn Lexvold) #6

I have trouble understanding some error messages, but others I am learning to figure out. I don’t know what that particular error message means: unexpected Println at end of statement


(Anyaddres) #7

This is maybe what you want to do. https://play.golang.org/p/UopgdBH15pJ
The map value is a []string. So you need to either create a list in place or create it as a separate variable and then assign it.


(surlac) #8

Use backticks for multiline strings. Also use untyped composite literal instead, which is shorter (see https://github.com/golang/go/issues/12854)
https://play.golang.org/p/9sgbLZaZjsl


(Cherolyn Lexvold) #9

That works :slight_smile:


(Cherolyn Lexvold) #10

Thanks :slight_smile:

This part I don’t understand:
var x []string = {“a”, “b”, “c”}
var m map[string]int = {“a”: 1}

type T struct {
V int
}
var s []*T = {{0}, {1}, {2}}

a := {1, 2, 3} // error: left-hand-type has no type specified


(Cherolyn Lexvold) #11

Also this:
Go already allows the elision of the type of a composite literal under certain circumstances. This proposal extends that permission to all occasions when the literal type can be derived.