【Go】始め‐ワックスペース

Go Go

概要

Go 1.18 で導入されたこの機能は、ワークスペースの概念をサポートし、複数の Go モジュールが互いに依存している大規模なプロジェクトや、複数のサブプロジェクトを同時に開発する際に特に便利です。

コードで見ましょう

一つ目のモジュールを作成

$ mkdir hello
$ cd hello
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello

golang.org/x/example/hello/reverseのパッケージを追加します。

$ go get golang.org/x/example/hello/reverse
go: downloading golang.org/x/example/hello v0.0.0-20240205180059-32022caedd6a
go: downloading golang.org/x/example v0.0.0-20240205180059-32022caedd6a
go: module golang.org/x/example/hello@upgrade found (v0.0.0-20240205180059-32022caedd6a), but does not contain package golang.org/x/example/hello/reserve
// ダウンロードしたらもう一度実行しまう。
$ go get golang.org/x/example/hello/reverse
go: added golang.org/x/example/hello v0.0.0-20240205180059-32022caedd6a

ソースを作成します。

$ vi hello.go
package main

import (
    "fmt"

    "golang.org/x/example/hello/reverse"
)

func main() {
    fmt.Println(reverse.String("Hello"))
}

実行してみます。

$ go run .
olleH

ワックスペースを作成します。

$ cd ..
$ go work init ./hello

go.workファイルを確認しましょう。

$ cat go.work
go 1.20

use ./hello

モジュールを指定して実行してみる

$ go run ./hello
olleH

Githubからexampleモジュールをcloneします

$ git clone https://go.googlesource.com/example
Cloning into 'example'...
Receiving objects: 100% (386/386), 347.50 KiB | 1.45 MiB/s, done.

Resolving deltas: 100% (133/133), done.
$

ワックスペースに追加してみます。

$ go work use ./example/hello

go.workの内容を確認します。

$ cat go.work
go 1.20

use (
        ./example/hello
        ./hello
)

exampleモジュールのに新しい関数を追加してみる

$ vi example/hello/reverse/int.go
package reverse

import "strconv"


func Int(i int) int {
    i, _ = strconv.Atoi(String(strconv.Itoa(i)))
    return i
}

作成したhelloモジュールから新規の関数Intを使ってみましょう。

$vi hello/hello.go
package main

import (
        "fmt"

        "golang.org/x/example/hello/reverse"
)

func main() {
        fmt.Println(reverse.String("Hello"), reverse.Int(123489))
}

実行してみる

$ go run ./hello
olleH 984321

go.workのおかげでhelloモジュールからexampleモジュールのreverseの関数の呼び出しもできます。

タイトルとURLをコピーしました