dryl34156
dryl34156
2019-03-07 10:46

同一项目中的多个模块

已采纳

I've been playing with Go modules and I was wondering what the best practice is in terms of the following directory structure:

project
├── go.mod
├── main.go
└── players
    ├── go.mod
    ├── players.go
    └── players_test.go

I was having problems importing the players package into my root project at first, but I noticed I could do this in the root go.mod file

module github.com/<name>/<project>

require (
    github.com/<name>/players v0.0.0
)

replace github.com/<name>/players => ./players

This then allows me to do import "github.com/<name>/players" in my main.go file.

Now this approach works and was taken from here but I'm not sure if that's the correct approach for this or whether this approach is just meant for updating a local package temporarily while it's outside version control.

Another option, that seems a little overkill, is to make every module its own repository?

TL;DR; - What's the best practice approach to having multiple modules within the same repository and importing them in in other modules / a root main.go file?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongxiaoyan4388 dongxiaoyan4388 2年前

    In general a module should be a collection of packages.

    But still you can create modules of single packages. As Volker said, this might only make sense, if you want these packages to have a different lifecycle. It could also make sense, when you want to import these modules from another project and don't want the overhead of the whole collection of packages.

    In General:

    A module is a collection of related Go packages that are versioned together as a single unit.

    Modules record precise dependency requirements and create reproducible builds.

    Most often, a version control repository contains exactly one module defined in the repository root. (Multiple modules are supported in a single repository, but typically that would result in more work on an on-going basis than a single module per repository).

    Summarizing the relationship between repositories, modules, and packages:

    1. A repository contains one or more Go modules.
    2. Each module contains one or more Go packages.
    3. Each package consists of one or more Go source files in a single directory.

    Source of the Quote: https://github.com/golang/go/wiki/Modules#modules

    To answer the question:

    You can do it the way you have shown in your approach:

    点赞 评论 复制链接分享