Go 1.18 Changes - Workspace


バージョンは2022、03、15 Go 1.18.主にWorkspace、Fuzzing、Genericsを紹介し、この記事ではWorkspaceを紹介します.
Workspaceとは?Go blogおよびRelease Notesには、次の説明があります.
The go command now supports a "Workspace"mode. If a go.work file is found in the working directory or a parent directory, or one is specified using the GOWORK environment variable, it will put the go command into workspace mode. In workspace mode, the go.work file will be used to determine the set of main modules used as the roots for module resolution, instead of using the normally-found go.mod file to specify the single main module.
In Go 1.18, we’ve addressed this with a new Go workspace mode, which makes it simple to work with multiple modules.
様々なモジュールを処理するために使われているように見えますが、具体的には分かりません.
ちょうど正式なチュートリアルあるので試してみます.

ハローディレクトリには、以下に示すハローがあります.作成go:
package main

import (
    "fmt"

    "golang.org/x/example/stringutil"
)

func main() {
    fmt.Println(stringutil.Reverse("Hello"))
}

そしてgo run example.com/helloと確認された.
今はワークスペースの時間です.

ワークスペースディレクトリに戻って、go work init hello、goをください.ワークという名前のファイルが作成され、その内容は以下のようになります.go命令はどのバージョンのGoを使用するかを示し,use命令は構築時にどのモジュールをメインモジュールとして使用するかを示す.したがって、ワークスペースの下にあるすべてのサブディレクトリのモジュールも影響を受けます.

ワークスペースディレクトリでgo run example.com/helloを試し、正常に動作しました.ワークスペース内のすべてのモジュールがメインモジュールと見なされているためです.したがって、モジュールの外でもそのモジュールのパッケージを参照することができる.go.ワークを一時的に無効にし、再度チェックするとexampleになります.com/helloモジュールが見つからないエラーが表示されます.
次はワークスペースのゴルフorg/x/exampleモジュールのローカルコピーを追加するとstringtilパッケージに新しい関数が追加されます.

クローンのサンプルモジュールがgo work useに追加された場合、go.仕事中にも反映されるものが見られます.go getで受信したstringtilバージョンの代わりに、私たちが修正したコードバージョンを使用することができます.
workspace/example/stringtilの下to upper.goファイルでToUpper関数を実装するには:
package stringutil

import "unicode"

// ToUpper uppercases all the runes in its argument string.
func ToUpper(s string) string {
    r := []rune(s)
    for i := range r {
        r[i] = unicode.ToUpper(r[i])
    }
    return string(r)
}
そしてworkspace/helloの下のhellogoファイルでは、新しく作成したToUpperにReverseを置き換え、go run example.com/helloを行うことで、修正バージョンのStringtilがよく反映されることを確認できます.

ここから歩きます.仕事がなければ例を挙げるcom/helloとは何か、どんなgoangか.org/x/exampleを使用するべきか分からないかもしれません.あるいはredirect directiveを使用すると、同じ効果が得られ、ワークスペースがより便利に見えます.