S
S
Sergey Romanov2020-03-31 19:29:11
go
Sergey Romanov, 2020-03-31 19:29:11

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

1 answer(s)
A
anaxita, 2021-07-03
@anaxita

Because after sending the true message to the channel, the function (goroutine) main ends and the application (everything) stops.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question