for {}和for i = 0之间的差异; i ++ {}进入

问题描述:

I am currently learming Go. I am readging the book An Introduction to programming in go

I am at the concurrency section and form what I understand I can see two way to define an infinite loop a go program.

func pinger(c chan string) {
    for i := 0; ; i++ {
        c <- "ping" 
    }
}

func printer(c chan string) {
   for {
       msg := <- c
       fmt.Println(msg)
       time.Sleep(time.Second * 1)
   }
}

I am wondering what is the use of the i variable in the pinger function. What is the best "go" way to declare an infinite loop ? I would say the the one in the printer function is better but as I am new to I might miss something with the declaration in the pinger function.

Thanks for all people who will help.

The i in the first loop is redundant; it's always best to get rid of unused variables therefore You should use a for{} in the pinger() function as well.

Here is a working example:

package main

import(
 "time"
 "fmt"
)

func main() {
    c := make(chan string)
    go printer(c)
    go pinger(c)
    time.Sleep(time.Second * 60)
}

func pinger(c chan string) {
    for{
        c <- "ping" 
    }
}

func printer(c chan string) {
   for {
       msg := <- c
       fmt.Println(msg)
       time.Sleep(time.Second * 1)
   }
}

Run on playground

The "best" way is to write code that is easy to read and maintain. Your variable i in func pinger serves no purpose and someone stumbling upon that code later on will have a hard time understand what it's for.

I would just do

func pinger(c chan string) {
  for {
    c <- "ping" 
  }
}