在Golang中,可以使用bufio包来进行对象的缓冲读写操作。

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

golang bufio in object

问题

我对Golang还比较新手,之前使用的是Python。

我在使用bufio时遇到了一些困难。

type fout struct {
    filename string
    fo File 
    bfo Writer
}

func (a *fout) init() {
    a.fo,_:=os.Open(a.filename)
    a.bfo:=bufio.NewWriter(fo)
}

基本上,我想创建对象,每个对象都有自己的文件名,并且要使用bufio。

有人可以帮帮我吗?

谢谢。

英文:

I'm fairly new to Golang; previously used Python.

I am having difficult time to apply bufio in the object.

type fout struct {
	filename string
	fo File 
	bfo Writer

}
func (a *fout) init() {
	a.fo,_:=os.Open(a.filename)
	a.bfo:=bufio.NewWriter(fo)
}

Basically, I like to create objects; each will have it's filename, and bufio will be used.

Can anyone help me please?

Thank you

答案1

得分: 1

代码示例中的几个要点:

  • 每次使用另一个包中的名称时,都需要使用包名作为前缀,所以fo File应该改为fo *os.File
  • 通常情况下,你需要将*bufio.Writer*os.File声明为指针(参考http://golang.org/pkg中的bufio和file文档)。
  • 对于像a.foa.bfo这样的属性赋值,你需要使用普通的=,而不是:=
  • 不要丢弃错误,特别是如果你习惯于使用异常,否则你将遇到难以调试的问题(对于用于学习的简单脚本,你可以使用if err != nil { panic(err) },但对于实际使用,你几乎总是希望返回错误)。

此外,你还可以参考一下以下资源:Go 之旅,从各种演讲博客文章中获取一些技巧和建议,也可以浏览一些开源的 Go 代码(Github 上的项目、标准库等),并在你想要了解语言的工作原理时,阅读令人惊讶的易读规范

英文:

Few things in the code sample:

  • Every use of a name from another package needs to be prefixed with the package name--so fo File has to be fo *os.File.
  • You normally declare *bufio.Writer and *os.File as pointers (see the bufio and file docs at http://golang.org/pkg)
  • You want plain =, not :=, for assigning to attributes like a.fo and a.bfo.
  • Don't throw away errors, particularly if you're used to exceptions, or you'll have impossible-to-debug problems. (For a trivial script for learning you can if err != nil { panic(err) }, but for real use, you almost always want to return them.)

It could also help to review the tour, pick up some tricks/advice from the various talks and blog posts, maybe walk through Go By Example (I admit I haven't persionally used it but sounds like it could be useful when getting started), look at some open-source Go code (projects on Github, the stdlib, anything), and run through the surprisingly readable spec once you're at the level where you want to know how the language really works.

huangapple
  • 本文由 发表于 2014年12月24日 00:44:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/27624522.html
匿名

发表评论

匿名网友

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

确定