golang cannot find module for local path [duplicat

2020-01-20 10:58发布

I want to push out some of API, from main package into separate package:

myapp/
    main.go
    myapi/
        myapi.go

Inside main.go i have

package main

import "./myapi"

...

And myapi.go just starts with:

package myapi

...

When I am trying to run main, it seems like it can't find my myapi #include. It gives me following error:

D:\go\myapp> go run .
build _/D_/go/myapp/myapi: cannot find module for path _/D_/go/myapp/myapi

I came from C/C++ world, and it's extremely unobvious, how to include from subfolder in golang. Could you help me with this?

1条回答
别忘想泡老子
2楼-- · 2020-01-20 11:18

Go uses something called Module Paths. These are paths that identify your packages. They are not necessarily related to the file system.

An example of a module path is github.com/hajimehoshi/ebiten.

If you're using Go modules, this is also the path Go automatically downloads it from.

If you're using $GOPATH, the path into the source of the module would be go/src/github.com/hajimehoshi/ebiten.

Initialize your module with a new module path using go mod init <module path>. Generally this will be your GitHub repository, without the https://. This will allow for both your and others code to be able accessible using that module path. myapi should then be accessible via import "github.com/username/repo/myapi".

If you still wish to use the old $GOPATH method, simply place your code inside go/src/<module path>. The method of accessing myapi is equivalent.

Read Using Go Modules and How to write Go code for more information.

查看更多
登录 后发表回答