施虞斌
施虞斌

Reputation: 21

How to assign a pointer to interface in Go

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?

Upvotes: 1

Views: 2083

Answers (2)

Oleg
Oleg

Reputation: 742

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

Upvotes: 2

bereal
bereal

Reputation: 34312

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.

Upvotes: 2

Related Questions