英文:
"Declared but not used" variable in for's condition expression
问题
我的直觉方法:
https://play.golang.org/p/6xzg7TK1IH
但它不起作用。
你能分享一些替代方法吗?
英文:
My intuitive approach:
https://play.golang.org/p/6xzg7TK1IH
and it doesn't work.
Can you share some alternative ways?
答案1
得分: 2
你声明了一个变量(moreline
),但你没有使用它。你有两个选择:要么将moreline
替换为下划线,这意味着你可以省略返回值。
for moreline {
line, _, err := bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
但更好的选择是使用ReadScanner
、ReadBytes('\n')
或ReadString('\n')
。
检查bufio.go
文件,你会得到对ReadLine
方法的描述:
ReadLine
是一个低级的读取行的原始方法。大多数调用者应该使用ReadBytes('\n')
或ReadString('\n')
,或者使用Scanner
。
在调用ReadLine
之后调用UnreadByte
将始终取消读取最后一个字节(可能是属于行尾的字符),即使该字节不是ReadLine
返回的行的一部分。ReadLine
要么返回一个非空行,要么返回一个错误,永远不会同时返回两者。
所以这将是一个更好的选择:
scanner := bufio.NewScanner(bio)
for scanner.Scan() {
line := scanner.Text()
fmt.Printf("%v\n", line)
}
英文:
You are declaring a variable (moreline
) which you don't use it. You have two options here: either to replace the moreline
with underscore, which means you can omit the return value.
for moreline {
line, _, err := bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
But a better option will be to use the ReadScanner
, ReadBytes('\n')
or ReadString('\n')
.
Checking the bufio.go
file this is what you get as description for the ReadLine
method:
> ReadLine is a low-level line-reading primitive. Most callers should
> use ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
Calling UnreadByte
after ReadLine
will always unread the last byte read (possibly a character belonging to the line end) even if that byte is not part of the line returned by ReadLine
. ReadLine
either returns a non-nil line or it returns an error, never both.
So this would be a better option:
scanner := bufio.NewScanner(bio)
for scanner.Scan() {
line := scanner.Text()
fmt.Printf("%v\n", line)
}
答案2
得分: 1
你使用了:=
,它会丢弃变量之前的内容。在该作用域中,你没有使用morelines
,因此会出现错误消息。
如果你事先声明变量并且不使用:=
,它就可以正常工作。函数ReadLine()
可能不会按照你期望的方式工作。
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
bio := bufio.NewReader(os.Stdin)
var line []byte
var err error
var moreline bool = true
for moreline {
line, moreline, err = bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
}
英文:
You use :=
which discards the previous contents of the variables. You don't use morelines
in that scope, thus the error message.
If you declare your variables beforehand and don't use :=
, it works fine. The function ReadLine()
might not do what you think it should do.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
bio := bufio.NewReader(os.Stdin)
var line []byte
var err error
moreline := true
for moreline {
line, moreline, err = bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论