Go言語でローカルパッケージをインポート

基礎からわかるGo言語には載っていなかったようなのでメモ。

パッケージのimportに関してよく見かける説明では、importするパッケージはGOPATH以下に配置されている必要がありますが、わざわざGOPATHにパスを追加して管理するのも面倒に感じます。
そういう場合は普通に相対パスでimportすればOKです。

以下のようなファイルがあり、

main.go
mystr/mystring.go

以下のような内容であれば実行できます。

main.go

package main

import (
	"./mystr"
	"fmt"
)

func main() {
	var message mystr.MyString = "OKOK"
	fmt.Println(message)
}

mystr/mystring.go

package mystr

type MyString string

ヘルプは以下のコマンドで見られます。

go help packages

該当箇所。

...
An import path that is a rooted path or that begins with
a . or .. element is interpreted as a file system path and
denotes the package in that directory.
...

基礎からわかる Go言語

基礎からわかる Go言語