Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use the functions of that interface by using an interface from one package in another package?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading