Let's say I have struct as that holds an interface;
type Client struct {
httpClient oop.HTTPClientInterface
}
Let's say I have an another struct as follows:
type HTTPImpl struct {
httpNotify HTTPNotificationInterface
}
this struct is initialized with the following function and single parameter which is interface.
func NewHTTPImpl(httpNotify HTTPNotificationInterface) {}
And assuming that this struct HTTPImpl implements all the methods defined inside but there's no explicitly saying or mapping between oop.HTTPClientInterface and HTTPImpl. Method names and signatures are same.
So, this is the part I don't understand,
Let's say Client struct is initialized and I want to set httpClient. Code below works. I don't know how.
1- c := NewClient()
2- c.Client = NewHTTPImpl(c)
3- if _, ok := c.Client.(*HTTPImpl)
How does this work? I don't understand. How does the code line 2 and line 3 work? Casting and passing a struct while waiting for an interface. And when I remove one of the interface method implementation from HTTPImpl, code gets underlined with a red color and requires it to be implemented.
What's the exact relationship here between interfaces and structs in Go here?
It is called runtime polymorphism. https://en.wikipedia.org/wiki/Runtime_polymorphism
Runtime checks if the type being fed implements all the necessary methods described by the interface.
Your IDE is checking what would happen if the code run and it's marking that it would fail.