I want to use the function in pageOne package along with interfaces and structs from pageTwo package. There is a very minor issue that I missed here. but I can’t find it and therefore I get the following error:
invalid memory address or nil pointer dereference
How can I use the functions of that interface by using an interface from one package in another package?
a.go
package pageTwo
import "fmt"
type Iface interface {
Run()
}
type Sface struct{ name string }
func (s *Sface) Fface(name string) {
s.name = name
fmt.Println(s.name)
}
and when I call the function it does not accept data inside. i.e. Run function needs to get name but it doesn’t accept
b.go
package pageOne
import "test/src/database"
type Iserver interface {
Get()
}
type Sserver struct {
Ins database.Iface
}
func (s *Sserver) Fserver(){
s.Ins.Run()
}
main.go
func main() {
x:=model.Sserver{}
x.Ins.Run()
}
>Solution :
You did not initialize the interface field in Sserver:
x:=model.Sserver{
Ins: someDatabaseInstance,
}
Your declaration of Sserver contains Ins, which is a field of type database.Iface. You have to set that to an implementation of that database interface.