Accessing local packages within a go module (go 1.11)

前端 未结 2 933
春和景丽
春和景丽 2020-12-04 07:02

I\'m trying out Go\'s new modules system and am having trouble accessing local packages. The following project is in a folder on my desktop outside my gopath.

My pro

2条回答
  •  我在风中等你
    2020-12-04 07:13

    Let me define this first modules are collections of packages. In Go 11, I use go modules like the following:

    If both packages are in the same project, you could just do the following: In go.mod:

    module github.com/userName/moduleName

    and inside your main.go

    import "github.com/userName/moduleName/platform"

    However, if they are separate modules, i.e different physical paths and you still want to import local packages without publishing this remotely to github for example, you could achieve this by using replace directive.

    Given the module name github.com/otherModule and platform, as you've called it, is the only package inside there. In your main module's go.mod add the following lines:

    module github.com/userName/mainModule
    
    require "github.com/userName/otherModule" v0.0.0
    replace "github.com/userName/otherModule" v0.0.0 => "local physical path to the otherModule"
    

    Note: The path should point to the root directory of the module, and can be absolute or relative.

    Inside main.go, to import a specific package like platform from otherModule:

    import "github.com/userName/otherModule/platform"
    

    Here's a gentle introduction to Golang Modules

提交回复
热议问题