Difference between for{} and for i=0; i++ {} in go

huangapple go评论82阅读模式
英文:

Difference between for{} and for i=0; i++ {} in go

问题

我目前正在学习Go语言。我正在阅读《Go语言编程入门》这本书。

我现在正在并发部分,根据我理解,我可以看到两种定义Go程序中无限循环的方式。

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)
   }
}

我想知道在pinger函数中的变量i有什么用。在Go语言中,最好的无限循环的声明方式是什么?我会说在printer函数中的方式更好,但作为一个新手,我可能在pinger函数的声明中漏掉了一些东西。

感谢所有愿意帮助我的人。

英文:

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 &lt;- &quot;ping&quot; 
    }
}

func printer(c chan string) {
   for {
       msg := &lt;- 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.

答案1

得分: 4

在第一个循环中的i是多余的;最好始终消除未使用的变量,因此在pinger()函数中也应该使用for{}

以下是一个可工作的示例:

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)
	}
}

在 playground 上运行

英文:

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(
 &quot;time&quot;
 &quot;fmt&quot;
)

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

func pinger(c chan string) {
    for{
        c &lt;- &quot;ping&quot; 
    }
}

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

Run on playground

答案2

得分: 2

“最好”的方法是编写易于阅读和维护的代码。在func pinger中,你的变量i没有任何用途,后来遇到这段代码的人将很难理解它的作用。

我会这样写:

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

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 &lt;- &quot;ping&quot; 
  }
}

huangapple
  • 本文由 发表于 2015年12月23日 17:58:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/34432977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定