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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)