duancan65665 2016-06-17 06:01
浏览 74


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 (


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 (

    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.

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



  • ¥50 悬赏帮写C++编程 诚信
  • ¥15 在竞速练习时输出和输入可以同时进行
  • ¥15 端口连接数为什么会有限制
  • ¥15 安卓数据提交之后格式不对
  • ¥15 需要数据库运行的图片
  • ¥15 如何获取vue-video-editor?
  • ¥100 vs2019 mfc程序如何实现64*64/48*48大小的真彩色工具栏
  • ¥15 全志v3s耳机音频输出口怎么外接功放
  • ¥15 华为ensp使用基本ACL限制公司网络访问
  • ¥15 帮我做下照片上的PLC题