#Pointer to interface not implementing

15 messages · Page 1 of 1 (latest)

inland kelp
#
package main

import "fmt"

type MyInterface interface {
    Build() string
}
type MyImplementingStruct struct{}

func (i MyImplementingStruct) Build() string { return "Hello World!" }

type MyOtherStruct struct {
    UsesInterfacePtr *MyInterface
}

func main() {
    // Works
    var a MyInterface
    a = MyImplementingStruct{}
    b := MyOtherStruct{
        UsesInterfacePtr: &a,
    }

    // Doesnt work
    d := MyImplementingStruct{}
    e := MyOtherStruct{
        UsesInterfacePtr: &d, // "&d *MyImplementingStruct doesnt implement *MyInterface" ??
    }

    fmt.Println(b)
    fmt.Println(e)
}

Is it necessary to define the type in var? It cant just be inferred?

potent robin
#

it could be it doesn't

#

inferring is tricky and it leads to dangerous bugs when it happens when programers aren't aware of it

#

wait no

#

that code is just wrong

elfin sinew
potent robin
#

You never want a pointer to an interface

inland kelp
#

🤔 why

potent robin
#

*almost

potent robin
inland kelp
#

👀

potent robin
#

if you want a pointer type, then you use a value interface which stores a pointer

inland kelp
#

Ok 2 learning points from this

  1. Yes you'd have to use var, so you can just do var a MyInterface = MyImplementingStruct{} if needed
  2. Interfaces are pointers, so don't need to make the struct pointers for this use case (I just wanted to be able to use nil)
#

tyvm

versed merlin
#
  1. Interfaces are pointers, so don't need to make the struct pointers for this use case (I just wanted to be able to use nil)
    In fact, an interface is a pointer plus plus. It also stored a pointer to the pointer's type so you can type assert it later. An interface will use double size (16 bytes on 64bit system) than a simple pointer (8 bytes on 64bit system) because it stored two pointers underlying