大家好, 我是 老麦, 一个运维老兵, 现在专注于 Golang,DevOps,云原生基础设施建设。
建议点击 查看原文 查看最新内容。
原文链接: https://typonotes.com/posts/2025/05/16/read-file-line-by-line-go124/
image
在 go 1.24 中新增加了两个标准方法 - strings.Lines()
和 bytes.Lines()
。
\n
拆分对象。Seq
的迭代对象。Seq
迭代对象可以接受一个 回调函数 或 使用 for
循环 进行遍历。
使用 回调函数 时, 可以通过 return false
提前终止遍历。
// ... omit
// 读取文件内容
seq := bytes.Lines(b)
func callback(line []byte) bool {
if bytes.HasPrefix(line, []byte("//")) {
// 提前结束
returnfalse
}
println(string(line))
returntrue
}
seq(callback)
在 使用 for
循环 遍历需要注意是
value
而非 slice index 或 map key。 类似 for _, line := range slice/map
for line := range seq {
if bytes.HasPrefix(line, []byte("//")) {
continue
}
println(string(line))
}