Greeting Lines
One greeting was a warm-up. Now do it for a whole list, and number the lines.
Go has no string concatenation operator you would want to use in a loop. The
idiom is to build a slice of lines and then join them once, with
strings.Join.
Task
Implement GreetAll(names []string) string in main.go. It returns one line
per name, joined by "\n":
1. Hello, Ada!
2. Hello, Grace!
3. Hello, Alan!
The rules:
- Lines are numbered from
1, not from0. - An empty name is greeted as
World, exactly like the last challenge:[]string{"Ada", "", "Alan"}gives2. Hello, World!in the middle. - No names at all gives the empty string,
"". Anilslice counts as no names. - There is no trailing newline.
Joinputs the separator between elements, which is precisely what you want here.
Hints
-
for i, name := range namesgives you the index and the value at once. The line number isi + 1. -
fmt.Sprintf("%d. Hello, %s!", i+1, name)formats one line.%dis an integer,%sa string. -
Collect the lines in a
[]stringandappendto it, thenstrings.Join(lines, "\n"). -
stringsis not imported yet. Add it, and note that Go refuses to compile a file that imports a package it never uses:import ( "fmt" "strings" ) -
strings.Joinof an empty slice is"", so the "no names" case needs no special handling.