importできません。
目次
呼び出される側のモジュールを作る
module helloworld go 1.21.4
helloworld.go
を作成する。
package helloworld import "fmt" func HelloWorld() { fmt.Println("Hello World!") }
呼び出す側を作る
- go-sampleというフォルダを作成して
go mod init sample
を実行する。 main.go
を作成する。ここでさっきのgo-helloworldをインポートする。
package main import "github.com/takurooo/go-helloworld" func main() { helloworld.HelloWorld() }
go mod tidy
を実行するとgithub.com/takurooo/go-helloworld
をdownloadするがmoduleの宣言がgithub.com/takurooo/go-helloworld
になっていないと表示される。
go: finding module for package github.com/takurooo/go-helloworld go: downloading github.com/takurooo/go-helloworld v0.0.0-20240104074603-37cc24b9797d go: found github.com/takurooo/go-helloworld in github.com/takurooo/go-helloworld v0.0.0-20240104074603-37cc24b9797d go: sample imports github.com/takurooo/go-helloworld: github.com/takurooo/go-helloworld@v0.0.0-20240104074603-37cc24b9797d: parsing go.mod: module declares its path as: helloworld but was required as: github.com/takurooo/go-helloworld
go run main.go
を実行してもmoduleがなくてエラーになる。
main.go:3:8: no required module provides package github.com/takurooo/go-helloworld; to add it: go get github.com/takurooo/go-helloworld