Answer the question
In order to leave comments, you need to log in
Why does this code work as I expect?
What exactly does not work as I expect. I am new to GO.
I have an infinite loop that I start and stop by sending a message to m[1] channel. But here's what's not clear, I'm passing go loop(m[1]); not by reference as far as I understand. Why when I send a message to m[1] it gets into the loop that was called before the building where I send the message.
I thought that this should be called with & or similar.
package main
import (
"fmt"
"time"
)
func loop(quit chan bool) {
n := 0
for {
select {
case <-quit:
break
default:
// do stuff. I'd call a function, for clarity:
fmt.Println(n)
time.Sleep(500 * time.Millisecond)
n++
}
}
}
func main() {
m := make(map[int]chan bool)
m[1] = make(chan bool)
go loop(m[1]);
time.Sleep(2 * time.Second)
m[1] <- true
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question