Home > Software engineering >  Assigning to Pointers of interfaces
Assigning to Pointers of interfaces

Time:01-01

I want to make sure I understand what is happening in the code below:

package main

import "fmt"

type Dummy interface {
    display()
}

type Str struct {
    int_data int
}

func (s Str) display() {
    fmt.Println(s.int_data)
}

func main() {
    var d_ptr *Dummy
    fmt.Println(d_ptr) //this displays nil... No surprises here
    var s_str Str = Str{4143}
    fmt.Println(s_str) //this displays {4143}... No surprises here
    //d_ptr = &s_str //This fails... A surprise here
    var d Dummy = s_str//This is OK..
    d_ptr = &d //This is OK..
    fmt.Println(d_ptr, *d_ptr)//Now its OK
}

Why can't I assign the address of a structure to a pointer of an interface(directly) if that structure implements the interface? Is it as simple as the address of the structure is not compatible or convertible to a interface pointer? Note: I know I can assign the structure to a variable of the type interface(Dummy) and then use that address in the assignment.

CodePudding user response:

In your code, d_ptr is a pointer to an interface. d_ptr does not implement the interface it is pointing to. Dummy and *Dummy are two different types. Thus, d_ptr=&s_str fails.

Note that you can look at an interface as a struct containing two fields: the pointer to the underlying object, and a reference to its type. A pointer to an interface is a pointer to that struct and can be used to modify that interface value. It has a very specific use case, such as json.Unmarshal, where if pass a pointer to an interface{}, the unmarshal function will create a new concrete struct, and initialize the passed interface to that struct.

  •  Tags:  
  • go
  • Related