英文:
Error when calling interface function?
问题
为什么当writer
(io.Writer
的实现)尝试调用Write()
函数时,会显示这个错误信息:
this.writer.Write未定义(*io.Writer类型没有Write字段或方法)
英文:
package main
import "io"
type MyClass struct{
writer *io.Writer
}
func (this *MyClass) WriteIt() {
this.writer.Write([]byte("Hello World!"))
}
Why is it that when writer
, which is an implementation of io.Writer
, tries to call the Write()
function, displays me this error
> this.writer.Write undefined (type *io.Writer has no field or method
> Write)
答案1
得分: 5
如makhov所说,这是因为在MyClass
的结构定义中,writer
是一个指向实现了Writer
接口的对象的指针,而不是指向实现了writer
接口本身的对象。因此,你的代码应该是:
package main
import "io"
type MyClass struct{
writer io.Writer
}
func (this *MyClass) WriteIt() {
this.writer.Write([]byte("Hello World!"))
}
或者
package main
import "io"
type MyClass struct{
writer *io.Writer
}
func (this *MyClass) WriteIt() {
(*(this.writer)).Write([]byte("Hello World!"))
}
通常情况下,第一种选项更合理(也更符合惯用法)。
英文:
As makhov said, it is because writer
in your struct definition of MyClass
is a pointer to something which implements the Writer interface, not something which implements the writer interface itself. As such, your code should either be:
package main
import "io"
type MyClass struct{
writer io.Writer
}
func (this *MyClass) WriteIt() {
this.writer.Write([]byte("Hello World!"))
}
or
package main
import "io"
type MyClass struct{
writer *io.Writer
}
func (this *MyClass) WriteIt() {
(*(this.writer)).Write([]byte("Hello World!"))
}
Typically it would make sense (and be more idiomatic) to do the first option.
答案2
得分: 2
使用 writer io.Writer
而不是 *writer io.Writer
。
英文:
Use writer io.Writer
without *
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论