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)
Use writer io.Writer
without *
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.