Home > Backend Development > Golang > How to Properly Structure and Reference Golang Modules Without Publishing?

How to Properly Structure and Reference Golang Modules Without Publishing?

Barbara Streisand
Release: 2024-12-01 09:53:10
Original
637 people have browsed it

How to Properly Structure and Reference Golang Modules Without Publishing?

How to Structure Golang Modules and Project Structure in the New Way

Since the introduction of modules in Go 1.11, the approach to structuring modules and projects has changed. This article explains the new way to reference a module from another directory, particularly in the absence of publishing.

Referencing Modules in a New Structure

Example:

Suppose you have the following directory structure:

\root\module1
\root\module2
Copy after login

You want to access module2 from module1 using its types and structs.

New Module Structure

Unlike the old approach that required placing modules in GOPATH, modules are now created and initialized using the go mod init command:

go mod init github.com/username/modulename
Copy after login

This command generates a go.mod file to track the module's dependencies and a go.sum file to store the dependency hashes.

Accessing Module 2 from Module 1

To access module2 from module1, you need to add module2 as a dependency in module1's go.mod file:

module github.com/username/module1

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

Once the dependency is added, you can import module2 into your code in module1 using the following syntax:

import "github.com/username/module2"
Copy after login

This will allow you to use the types and structs defined in module2 within your code in module1.

The above is the detailed content of How to Properly Structure and Reference Golang Modules Without Publishing?. 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