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

How Do I Reference Go Modules from Outside the GOPATH?

Linda Hamilton
Release: 2024-11-27 20:27:15
Original
600 people have browsed it

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"
)
Copy after login

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
Copy after login

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"
)
Copy after login

File Structure

Assuming the following file structure:

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

└── module2
    ├── go.mod
    └── module2.go
Copy after login

go.mod Files

Module1:

module github.com/username/module1

require (
    github.com/username/module2 v0.0.1
)
Copy after login

Module2:

module github.com/username/module2

go 1.13
Copy after login

main.go (Module1)

package main

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

func main() {
    fmt.Println(module2.Name())
}
Copy after login

module2.go (Module2)

package module2

import "fmt"

func Name() string {
    return "Module 2"
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template