LoginSignup
0
0

More than 1 year has passed since last update.

Go ローカルで他のモジュールの関数を呼び出す方法

Posted at

ローカルで他のモジュールの関数を呼び出す方法

ディレクトリーの構成など全て公式のチュートリアルに沿っています。
Tutorial: Getting started with multi-module workspaces

ディレクトリー構成
/greetings
    - greetings.go
/hello
    - hello.go
greetings/greetings.go
package greetings

import "fmt"

func Hello(name string) string {
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}
hello/hello.go
package main

import (
    "fmt"
)

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

go.mod ファイルを作る

greedingsとhelloのディレクトリー内でgo.modを作る。
ここではexample.com/としているがgithub.com/(自分のアカウント)などの一意な名前の方が好ましい

#greedingsディレクトリーで以下のコマンドラインを実行
go mod init example.com/greedings

#helloディレクトリーで以下のコマンドラインを実行
go mod init example.com/hello

作成したモジュールをローカル環境に紐づける

ローカルで example.com/greetings コードを見つけられるようにする。

#helloディレクトリーで以下のコマンドラインを実行
go mod edit -replace example.com/greetings=../greetings

実行後の hello/go.modはこのようになる

module example.com/hello

go 1.20

replace example.com/greetings => ../greetings

依存関係を同期する

example.com/greetings のモジュールの依存関係を同期させる。

#helloディレクトリーで以下のコマンドラインを実行
go mod tidy

実行後の hello/go.modはこのようになる

module example.com/hello

go 1.20

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000

実行

hello.goにexample.com/greetingsのモジュールをインポートする

package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

実行

go run hello.go
0
0
0

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
0
0