I'm trying to pass a slice of pointers to structs that implement the interface LogicAdapter. Here's my code:
main.go:
var adapters[]LogicAdapter
adapter1 := &ExampleAdapter{}
fmt.Printf("Addr: %p\n", adapter1)
adapters = append(adapters, adapter1)
bot := ChatterBot{"Charlie", MultiLogicAdapter{adapters}}
bot.getResponse("test", 0)
multiadapterlogic.go:
type MultiLogicAdapter struct {
adapters []LogicAdapter
}
func (logic *MultiLogicAdapter) process(text string, session int) string {
//response := logic.adapters[0].process(text, session)
response := ""
for _, adapter := range logic.adapters {
fmt.Printf("Addr: %p\n", &adapter)
}
_ = response
return ""
}
The output of main is:
Addr: 0x5178f0
Addr: 0xc42000a340
I didn't include LogicAdapter because I don't think it's necessary.
I don't like to fill this with much code, but here's ChatterBot if it makes things easier to understand (but keep in mind that bot.getResponse
calls process
, that's it)
chatterbot.go
type ChatterBot struct {
Name string
MultiLogicAdapter
}
func (bot *ChatterBot) getResponse(text string, session int) string {
response := bot.process(text, session)
_ = response
return ""
}
First of all, I had the idea of storing pointers to LogicAdapters, in this way
var adapters[]*LogicAdapter
but everytime I tried to insert the adapter1 pointer there, I got:
*LogicAdapter is pointer to interface, not interface
so I discovered this and learned this:
When you have a struct implementing an interface, a pointer to that struct implements automatically that interface too. That's why you never have *SomeInterface in the prototype of functions, as this wouldn't add anything to SomeInterface, and you don't need such a type in variable declaration (see this related question).
So I decided to leave the adapters[]
declaration as you see in the code. The problem is that besides adapters
storing a pointer to adapter1
, when it gets printed in MultiLogicAdapter
, it's another address. I know that I'm passing adapters
to MultiLogicAdapter
as a copy, but the copy would have the same references to adapter1
. So what's happening?
Why I'm iterating through pointers? Because of this: https://www.goinggo.net/2013/09/iterating-over-slices-in-go.html If I don't, I'll be creating lots of unecessary copies.