lundi 5 juin 2023

Golang import package on runtime

I have two base github.com packages: github.com/xxx/package1 and github.com/xxx/package2

In the package1, I create a core folder and define a struct with a function:

package core

import (
    "fmt"
    "go/importer"
)

type Test struct {}

func (navi *Test) Run() {
    pkg, err := importer.Default().Import("github.com/xxx/package2/core")

    if err != nil {
        fmt.Print(err)
    }

    return
}

In the package2, I also create a core folder and a struct with a function:

package core

import "fmt"

type Hello struct {

}

func (hello *Hello) Test() {
    fmt.Print("Test\n")
}

I create a main.go file in the package2 with code:

package main

import (
    "fmt"
    "github.com/xxx/package1/core"
)

func main() {
    test := &core.Test {}

    test.Run()
}

I pushed both two this packages to the github.

On the package2, I use the go get command to download two above packages, then execute command "go run main.go"

However, I get the message can't find import: "github.com/xxx/package2/core"

If I use the import statement and import directly the github.com/xxx/package2/core, I can use the struct Hello under this package.

How can I resolve this error?





Aucun commentaire:

Enregistrer un commentaire