Telechargé par mail

WebClicker.org - Student - Review Questions

publicité
WebClicker.org - Student - Review Questions
1/29/19, 4(23 PM
Given the following function:
import (
"fmt"
"time"
)
func numbers() chan int {
ch := make(chan int)
go func() {
for number := 0; number < 10; number++ {
time.Sleep(1 * time.Second)
ch <- number
}
close(ch)
}()
return ch
}
Which main routine is guaranteed to print all 10 numbers without error?
// Option A
func main() {
ch := numbers()
for {
n, ok := <-ch
if !ok {
break
}
fmt.Printf("%d ", n)
}
fmt.Println()
}
// Option B
func main() {
ch := numbers()
go func() {
http://college.webclicker.org/student/?menu=review_question_view&sid=12430&id=4601&popup=1&adjust=1
Page 1 of 2
WebClicker.org - Student - Review Questions
1/29/19, 4(23 PM
for {
n, ok := <-ch
if !ok {
break
}
fmt.Printf("%d ", n)
}
}()
time.Sleep(10 * time.Second)
fmt.Println()
}
// Option C
func main() {
ch := numbers()
done := time.NewTimer(time.Second * 10)
Forever:
for {
select {
case n := <-ch:
fmt.Printf("%d ", n)
case <-done.C:
break Forever
}
}
fmt.Println()
}
// Option D
func main() {
ch := numbers()
for n := range ch {
fmt.Printf("%d ", n)
}
fmt.Println()
}
http://college.webclicker.org/student/?menu=review_question_view&sid=12430&id=4601&popup=1&adjust=1
Page 2 of 2
Téléchargement