LoginSignup
16
14

More than 5 years have passed since last update.

Goのパッケージパスとパッケージ名は異なってもよいか?

Posted at

ふと疑問に

Goではパッケージパスの最後の要素は配下の(goファイルの)パッケージ名と同じにするのが慣例だが「異なっていてもよい」のでしょうか?

では確認を

パスツリー

$GOPATH/
   +--src/
      +--japan/
         +--main.go
         +--area/
            +--chugoku.go

変更前:パッケージパスの最後の要素とパッケージ名が同じ

最後の要素:area
パッケージ名:area

area/chugoku.go
// パッケージ名:area
package area

import "fmt"

func Okayama() {
    fmt.Println("ピーチ")
}
main.go
package main

import (
    // パッケージパスの最後の要素:area
    "japan/area"
)

func main() {
    // パッケージ名:area
    area.Okayama()
}

実行結果

$ go run main.go 
ピーチ

変更後:パッケージパスの最後の要素とパッケージ名が異なる

最後の要素:area
パッケージ名:chugoku

area/chugoku.go
// パッケージ名:area -> chukoku
package chugoku

import "fmt"

func Okayama() {
    fmt.Println("ピーチ")
}
main.go
package main

import (
    // パッケージパスの最後の要素:変更なし
    "japan/area"
)

func main() {
    // パッケージ名:area -> chugoku
    chugoku.Okayama()
}

実行結果

$ go run main.go 
ピーチ

結論としては

import文ではパッケージでなくパス名(文字列なのも納得)を指定しているため、パッケージパスの最後の要素は配下の(goファイルの)パッケージ名と「異なっていてもよい」です。

直近で見ていた mackerel-agent-plugins でも使われていました。

16
14
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
16
14