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