LoginSignup
0
1

More than 1 year has passed since last update.

Go ファイル分割

Posted at

初めに

ファイルを分けて管理したい
Nodeみたいに const hoge = require("hoge")すればよいだけではないらしい
備忘録として残しておく

同一package(同じディレクトリ)で分ける

main.go
package main

func main() {
	// 同一packageなのでimportが必要ない
	Bar()
}
bar.go
package main

import (
	"fmt"
)

func Bar() { // 外部ファイルで使用する場合、頭文字は大文字
	fmt.Println("bar")
}
# go.modがある場合
# runやbuild時に全てのmain packageを指定する
go run main.go bar.go

# go.modがある場合
go run .

別package(ディレクトリ)に分ける

go.modが必要
go mod init go_test

go_test
  - main.go
  bar
    - bar.go
package main
// bar.goまでのpath
// go mod initで決めたmodule名から始める
import "go_test/bar" 

fun main() {
  bar.Bar() // package名.関数名
}
bar/bar.go
package bar // DirNameと同じにする

import "fmt"

func Bar() { // public(大文字始め)関数にする
	fmt.Println("bar")
}

終わりに

go mod init [module名] module名が結構大事だと思うのですが、githubに上げない時はiとか適当な名前にしちゃいます。
あとからgithubに上げようと心変わりしたら変更がめんどくさそうですね・・・

参考

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