英文:
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 <- "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.
答案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)
}
}
英文:
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)
}
}
答案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 <- "ping"
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论