简体   繁体   中英

Can't import local project from other project: cannot find module providing package <package_name>

I have a project I am working on named project1 .
Couple of months ago I worked on project2 which contains package named engine and I want to use it inside project1 .
These projects are local so I read here how to import local projects and tried it but received an error:

Cannot resolve file `project2`

One interesting thing is that when I type the name of project2 in the import(..) section, Goland identify it as module but after I press on it I received the error that it can't be resolve.

With Goland I have an option to run sync packages of 'project1' but when I pressed on it I also received an error:

project1/pkg/utils imports
    project2: cannot find module providing package project2

I also tried to create vendor folder in project1 and copy-paste the whole project2 beneath the vendor folder but it still didn't help.

Any idea why it doesn't being resolve?

If you have both of your projects under your $GOPATH , you can check out this example for importing projects.

EDIT: If you are using go modules and want to import local modules, then you can make use of the replace directive. So, basically you have to add in your go.mod of your Project1 these lines:

require /$module-name-project2/$package-name v0.0.0

replace $module-name-project2/$package-name => ../$localpath-to-project2

More info here

A quick example (both my projects are outside of $GOPATH and using go modules ):

  1. Project1 is located under .../go-experiments/project1

main.go :

package main

import "go-experiments/project2/greeting"

func main() {
    println("How to greet?")

    greeting.English()
}

go.mod :

module go-experiments/project1

require go-experiments/project2/greeting v0.0.0

replace go-experiments/project2/greeting => ../project2

go 1.14
  1. Project2 is located under .../go-experiments/project2 greeter.go :
package greeting

func English() {
   println("hi, i am boo")
}

go.mod :

module go-experiments/project2

go 1.14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM