2
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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use writer io.Writer without *

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.