Home  >  Article  >  Backend Development  >  How Do I Reference Go Modules from Outside the GOPATH?

How Do I Reference Go Modules from Outside the GOPATH?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 20:27:15571browse

How Do I Reference Go Modules from Outside the GOPATH?

Referencing Modules from Non-GOPATH Directories

The introduction of Go modules in Go 1.11 introduced changes in the referencing of modules and packages from non-GOPATH directories.

Old Way

Traditionally, Go modules were required to reside within the GOPATH. Modules and packages within this directory could be imported using the following syntax:

import (
    "github.com/username/modulename/subpackage"
)

New Way

With Go modules, this approach has changed. Packages can now reside outside of GOPATH. To reference a package from another directory:

Initializing a Module

Initialize a new module using the go mod init command:

go mod init github.com/username/modulename

This creates go.mod and go.sum files in the current directory.

Import Statements

Use import statements to reference packages from other directories. For example, if Module2 is located at /root/module2, and contains a package named module2, the import statement in Module1 will be:

import (
    "github.com/username/module2"
)

File Structure

Assuming the following file structure:

\root
└── module1
    ├── go.mod
    └── main.go

└── module2
    ├── go.mod
    └── module2.go

go.mod Files

Module1:

module github.com/username/module1

require (
    github.com/username/module2 v0.0.1
)

Module2:

module github.com/username/module2

go 1.13

main.go (Module1)

package main

import (
    "fmt"
    "github.com/username/module2"
)

func main() {
    fmt.Println(module2.Name())
}

module2.go (Module2)

package module2

import "fmt"

func Name() string {
    return "Module 2"
}

By following these steps, you can reference modules from non-GOPATH directories, enabling the reuse of code and modularity in Go projects.

The above is the detailed content of How Do I Reference Go Modules from Outside the GOPATH?. 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