Home >Backend Development >Golang >How to Effectively Organize Go Code Using Internal Packages with Modules?

How to Effectively Organize Go Code Using Internal Packages with Modules?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 14:12:24947browse

How to Effectively Organize Go Code Using Internal Packages with Modules?

Understanding Internal Packages and Their Usage

Question:

How do I effectively organize Go code using "internal" packages?

Initial Problem:

Despite placing the project outside the GOPATH, importing internal packages from main.go fails, unless the relative path is used (e.g., "./internal/foo|bar").

Introduction of Modules:

With the introduction of modules in Go v1.11 and above, placing the project inside $GOPATH/src is no longer necessary. Instead, you need to create a go.mod file to specify the location of each module.

Example:

Consider the following project structure:

project/
  go.mod
  main.go

  internal/
    bar/
      bar.go
      go.mod
    foo/
      foo.go
      go.mod

go.mod Files:

The go.mod files for the internal packages are simple:

module bar

go 1.14
module foo

go 1.14

Code in Internal Packages:

// bar.go
package bar

import "fmt"

// Bar prints "Hello from Bar"
func Bar() {
    fmt.Println("Hello from Bar")
}

// foo.go
package foo

import "fmt"

// Foo prints "Hello from Foo"
func Foo() {
    fmt.Println("Hello from Foo")
}

main.go:

// main.go
package main

import (
    "internal/bar"
    "internal/foo"
)

func main() {
    bar.Bar()
    foo.Foo()
}

Project go.mod File:

The project go.mod file informs Go about the internal packages and their locations:

module project

go 1.14

require internal/bar v1.0.0
replace internal/bar => ./internal/bar
require internal/foo v1.0.0
replace internal/foo => ./internal/foo

Important Notes:

  • The names in the require section are for Go's internal use and can be arbitrary.
  • The version numbers in the require section don't matter in this context.
  • The replace lines specify where Go can find the internal packages.

Execution:

Running the main.go file will now print:

Hello from Bar
Hello from Foo

This example demonstrates how to effectively use internal packages within a Go project using modules.

The above is the detailed content of How to Effectively Organize Go Code Using Internal Packages with Modules?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn