I am trying to import from “modules” pkg. Here is how main.go and modules/helper.go look like:
path main.go:
package main
import (
"fmt"
"interface_hello_1/modules"
)
type Infoer interface {
GetName() []Info
}
type Info struct {
Name string
Age int
}
func (i Info) GetName() []Info {
Infos := []Info{
{Name: "Foo", Age: 3},
}
return Infos
}
func infoPrint(i Infoer) {
fmt.Println(i.GetName())
}
func main() {
in := Info{}
var i Infoer = in
fmt.Println(i.GetName()) // Works
// From modules
n1 := modules.Info{}.GetName()
// Need guidance here... to make use of interface
var i1 Infoer = n1
i1.GetName()
}
path modules/helper.go:
package modules
type Info struct {
Name string
Age int
}
func (t Info) GetName() []Info {
Infos := []Info{
{Name: "Bar", Age: 4},
}
return Infos
}
Tried doing something like below; It is working. I am not quite sure if this is right way to go or there can be some more elegant way to do in GO.
path main.go:
package main
import (
"fmt"
"interface_hello_1/modules"
)
// Infoer Interface
type Infoer interface {
GetName() []Info
}
// Info struct to hold Name & Age; Implements Infoer interface
type Info struct {
Name string
Age int
}
// GetName Method
func (i Info) GetName() []Info {
Infos := []Info{
{Name: i.Name, Age: i.Age},
}
return Infos
}
func infoPrint(i Infoer) {
fmt.Println(i.GetName())
}
func main() {
in := Info{Name: "Foo", Age: 3}
var i Infoer = in
fmt.Println(i.GetName()) // Works
// From modules
n1 := modules.Info{}.GetName()
var in1 Info
for _, item := range n1 {
in1.Name = item.Name
in1.Age = item.Age
}
var i1 Infoer = in1
fmt.Println(i1.GetName())
}
path modules/helper.go:
package modules
type Info struct {
Name string
Age int
}
func (t Info) GetName() []Info {
Infos := []Info{
{Name: "Bar", Age: 4},
}
return Infos
}
Both types are different, and they also do not share a common interface.
main.Infoer requires the type to implement a method GetName() which returns something of type []main.Info, though modules.Info.GetName() does return []modules.Info.
So let me say it again, you need to extract the types and interfaces from main and move them to another package, modules or somewhere else.