1
package main

import "fmt"

type intr interface {
    String() string
}

type bar struct{}

func (b *bar) String() string {
    return "bar"
}

type foo struct {
    bar *intr
}

func main() {
    bar1 := bar{}
    foo1 := foo{bar: &bar1} 
    fmt.Println(foo1)
}

I get a compile-time error:

cannot use &bar1 (type *bar) as type *intr in field value: *intr is pointer to interface, not interface

Why is this error happened? How to assign foo.bar?

2 Answers 2

2

You're assigning it to a pointer to the interface. After changing the field type to interface it will work:

type foo struct {
    bar intr
}

Pointers to interfaces are quite rarely needed.

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

Comments

2

Uber-go style guide pointers-to-interfaces contains exact answer to your question,

You almost never need a pointer to an interface. You should be passing interfaces as values—the underlying data can still be a pointer. An interface is two fields: A pointer to some type-specific information. You can think of this as "type." And a data pointer. If the data stored is a pointer, it’s stored directly. If the data stored is a value, then a pointer to the value is stored. If you want interface methods to modify the underlying data, you must use a pointer.

My recommendation is to get acquainted with it as soon as possible,

Hope it helps

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.