调用接口函数时出错?

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

Error when calling interface function?

问题

为什么当writerio.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 *

huangapple
  • 本文由 发表于 2015年2月16日 03:54:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/28530437.html
匿名

发表评论

匿名网友

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

确定