简体   繁体   中英

Getting response from function without return - Golang

I have a service function in Golang where running an endless for loop. I wanted to get data from this function without return. What is the best solution, a channel, or io.Writer? The function and where I call it in a different package, because the funcion in package something while where I call it is the main. There is an example with channels:

func Check(dst string, w chan string) bool {    
  for {
    w <- data
  }
  return false
}

On the otherside where I call this function:

var wg sync.WaitGroup
func main() {
    messages := make(chan string, 10)

    wg.Add(3)
    go checking("10.1.1.1", messages)
    msg := <-messages
    fmt.Println(msg)
    wg.Wait()
}

func checking(ip string, msg chan string) {
    defer wg.Done()
    w := worker.ContainerAliveIndicator{}
    w.Check(ip, msg)
}

In this case I only get the first message what the function take to the channel.

The channel is a good option. To read all messages, just read from channel in a loop until it closes:

func check(s string, ch chan<- string) {
    for i := 0; i < 5; i++ { 
        //this could go forever, or until some condition is met
        ch <- fmt.Sprintf("I did something %s %d", s, i)
        time.Sleep(time.Millisecond)
    }
    close(ch)
}

func main() {
    ch := make(chan string)
    go check("FOO", ch)
    for msg := range ch { //will break when ch closes
        fmt.Println(msg)
    }
    fmt.Println("DONE!")
}

playground

Another option is passing a callback into the function:

func check(s string, cb func(string)) {
    for i := 0; i < 5; i++ { 
        //this could go forever, or until some condition is met
        cb(fmt.Sprintf("I did something %s %d", s, i))
        time.Sleep(time.Millisecond)
    }
}

func main() {
    msgs := []string{}
    check("FOO", func(s string) { msgs = append(msgs, s) })
    fmt.Println(msgs)
}

playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM