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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里