Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

How to use local packages in Go language (Go Moludes)

I was writing a program in Golang and the program was getting long, so I decided to break it up into packages.

configuration

The directory structure is as follows.

.
|-- a
|   `-- a.go
|-- b
|   `-- b.go
`-- main.go

procedure

Square Needle

Use Go Modules to turn your program into a single module and specify the package by the path from the module.

Module Configuration

Make the program into a module with an appropriate name.

go mod init test-module

A file named go.mod is created in the directory

module test-module

go 1.14

treatment

Load from import with "\/\".

package main

import(
    "test-module/a"
    "test-module/b"
)

func main(){
    a.Test()
    b.Test()
}

Go Modules are so useful.

Go Modules seems to be a feature that collectively manages the packages used by the program.

It is very convenient because go build will automatically install the packages listed in import without having to install each of the import packages one by one with go get. (Installation by go get is also possible.)

When a package is installed in go get or go build, it is appended to the go.mod file.

If you have the go.mod file, it will automatically install the packages listed in it at build time, so you only need go build when setting up in a new environment where no packages are installed, such as Docker, and you do not need to do go get. This is very convenient!

It seems like you can do things like fixing the version of the package being used.

It is like npm/package.json in JavaScript.

import (
    "./a"
    "./b"
)

You can use local packages with relative paths as "Go Modules", but I will actively use Go Modules from now on because the other features are super convenient.

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com