LoginSignup
1
0

More than 1 year has passed since last update.

Go言語のモジュール実装

Posted at

モジュールの実装方法と実装したモジュールを利用したmainモジュールを実行するところをできるだけ簡略化して紹介します。

モジュール用の作成

モジュール用のディレクトリを生成

mkdir greetings
cd greetings

モジュールの初期化

go mod initコマンドで現在のディレクトリをルートとする新しいモジュールを初期化(go.modファイルを生成)します。
※go.modファイルはまだ存在していてはなりません。

go mod init example.com/greetings
# go: creating new go.mod: module example.com/greetings

モジュールの実装

package greetings

import "fmt"

// 大文字から始まる関数はpublic扱いになるので、Hello関数はimportしたモジュールから参照できます。
func Hello(name string) string {
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

mainモジュールの組み込み

mainモジュール用のディレクトリを生成

mkdir hello
cd hello

mainモジュールの初期化

go mod initコマンドを実行します。

go mod init example.com/hello
# go: creating new go.mod: module example.com/hello

mainモジュールの実装

package main

import (
    "fmt"

    "example.com/greetings" // 現時点でこんなパスのモジュールは存在しません。
)

func main() {
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

ローカルに実装されたモジュールの参照

example.com/greetingsは公開されていないので、importされた時に、ローカルの../greetingsを参照するようにgo.modを書き換えるgo mod editコマンドを実行します。

go mod edit -replace example.com/greetings=../greetings

モジュールの依存関係の整理

go mod tidyを使ってgo.modファイルがモジュールのソースコードと一致することを確認、現在のモジュールと依存関係を構築するために必要な不足しているモジュールを追加、利用してないモジュールを削除、go.sumに不足しているエントリを追加と不要なエントリを削除します。

go mod tidy
# go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000

実行

go run .
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0