LoginSignup
0
0

More than 3 years have passed since last update.

Goで自作のパッケージをインポートする

Last updated at Posted at 2021-03-05

自分用にメモ

「スターティングGo言語」を進めていましたが、Goモジュールのサポートを使って自作パッケージをインポートしてみたかったのでやってみました。
Goのバージョンは1.13以上にしてください

go env

terminal
$ go env GO111MODULE
on

ディレクトリ構成

zoo
├── animals
│   ├── elephant.go
│   ├── monkey.go
│   └── rabbit.go
└── main.go

animalsパッケージ

呼び出すと食べ物を返す

elephant.go

package animals

func ElephantFeed() string {
    return "Grass"
}
monkey.go

package animals

func MonkeyFeed() string {
    return "Banana"
}
rabbit.go

package animals

func RabbitFeed() string {
    return "Carrot"
}

mainパッケージ

main.go
package main

import (
    "fmt"
    "go_mod/animals"
)

func main()  {
    fmt.Println(animals.ElephantFeed())
    fmt.Println(animals.MonkeyFeed())
    fmt.Println(animals.RabbitFeed())
}

go.modの作成

terminal
zooディレクトリで
$ go mod init go_mod
go: creating new go.mod: module go_mod

確認
$ cat go.mod
module go_mod

go 1.15

go buildの実行

terminal
$ go build /hoge/zoo/main.go

go run main.go

terminal
$ go run main.go
Grass
Banana
Carrot
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