Chapter 6 - Slices
Exercise 1: The Slice Operator
Define a printLines
function that takes a slice of strings as a parameter, and prints each element of that slice on a separate line.
Then, in main
, get a slice of the daysOfWeek
array containing just the weekdays: “Monday”, “Tuesday”, “Wednesday”, “Thursday”, and “Friday”. Pass that slice to printLines
.
Solution
package main
import "fmt"
// YOUR CODE HERE: Define a printLines function.
func printLines(lines []string) {
for _, line := range lines {
fmt.Println(line)
}
}
func main() {
daysOfWeek := [7]string{"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"}
// YOUR CODE HERE: Get a slice containing just the
// weekdays.
weekdays := daysOfWeek[1:6]
// Pass that slice to printLines.
printLines(weekdays)
}
Output:
Monday
Tuesday
Wednesday
Thursday
Friday