duancan65665 2016-06-17 06:01
浏览 74
已采纳

默认情况下是否可能不包含subdir中的Golang软件包?

I am using a golang package, say name pkgfoo; and the author explicitly said if we want to use a package subpkg under pkgfoo, I need to explicitly import subpkg. I don't understand the reason behind it. Isn't the subpkg automatically imported if I import the top pkg in Golang?

package main

import (
    "myownpackage"

    "github.com/usera/pkgfoo"
    "github.com/usera/pkgfoo/subpkg"
)

func main() {
    // Use functions in pkgfoo, and use functions in pkgfoo/subpkg
    // ......
    http.HandleFunc("/login", login)
    err := http.ListenAndServe(":9090", nil) // setting listening port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

My question is whether I really need import "github.com/usera/pkgfoo/subpkg" statement.

  • 写回答

1条回答 默认 最新

  • dougu3591 2016-06-17 06:08
    关注

    Go packages are constructed from one or more source files, which are organized into folders in the file system. Source files of the same package must be in the same folder.

    But in Go there is no "package hierarchy", the "subpackage" term simply refers to the folder of a package being a subfolder of another. We often organize packages to be in folders being subfolders of others because there is some connection between those packages (e.g. a package is used only by another being in the parent folder; or a package in a subfolder is a specific or more special implementation of the package in the parent folder; or simply just a logical grouping - see the end of the answer).

    So whenever you do

    import "github.com/usera/pkgfoo"
    

    It only imports pkgfoo and no other packages sharing the same path as prefix. If you need github.com/usera/pkgfoo/subpkg too, you also need to explicitly import it:

    import (
        "github.com/usera/pkgfoo"
        "github.com/usera/pkgfoo/subpkg"
    }
    

    The Go Blog: Package names on directories used in the standard library:

    Directories. The standard library uses like directories crypto, container, encoding, and image to group packages for related protocols and algorithms. There is no actual relationship among the packages in one of these directories; a directory just provides a way to arrange the files. Any package can import any other package provided the import does not create a cycle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题