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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度