How to pass struct returned from different packge in function defined in main.go

!Newbie Alert!

I am trying to get struct from a helper package (to main.go) and then pass that to a simple function defined in main.go.

Helper package:

path : modules/helper.go

package modules

type Test struct {
    Name string
}

func GetString() Test {
    t := Test{Name: "bar"}
    return t
}

main.go:

package main

import (
    "fmt"
    "learnGo/modules"
)

type Info struct {
    Name string
}

func printName(s Info) Info {
    return s

}

func main() {
    i := Info{Name: "foo"}

    resp := printName(i)
    fmt.Println(resp)

    // From module

    j := modules.GetString()
    resp1 := printName(j)
    fmt.Println(resp1)

}

Error :

./main.go:26:20: cannot use j (type modules.Test) as type Info in argument to printName

I understand that it is failing because function printName expects Info struct whereas then return typee os modules.Test.

What is the best way to deal with this situation? Interface in function parameter?

Thanks in Advance.

That could be a solution. Make both Test and Info implement an Interface that is accepted by printName.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.