为什么我不能导入pkg"内置"?

时间:2014-06-02 12:29:26

标签: go built-in

cat test.go

package main

import "builtin"

func main() {
    return
}

go run test.go

can't find import: "builtin"

我只是很好奇,因为该文件存在且已正确打包。但不能像其他包一样导入。

/usr/local/go/src/pkg/builtin/builtin.go

2 个答案:

答案 0 :(得分:4)

导入包时,编译器(或至少是gc编译器)会搜索已编译的包。

您可以在来源中看到此代码:http://golang.org/src/cmd/gc/lex.c?#L578

特别是,它不会搜索.go文件:假设已经构建了这些文件。与例如C ++相比,这是一个很大的胜利,因为每个包都可以编译一次,依赖它的代码可以使用已经编译的版本。

那么为什么“内置”不会被构建,即使它作为一个包存在?好吧,在构建源文件之前,在构建依赖关系的代码部分中忽略它是特殊的:http://golang.org/src/cmd/go/build.go?#L558

答案 1 :(得分:4)

您不需要导入它。默认导入。

来自http://golang.org/pkg/builtin

Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers. 
从golang.org/pkg/builtin开始)

如果你看一下http://golang.org/src/pkg/builtin/builtin.go的内容 您会注意到只有声明

    // The copy built-in function copies elements from a source slice into a
    // destination slice. (As a special case, it also will copy bytes from a
    // string to a slice of bytes.) The source and destination may overlap. Copy
    // returns the number of elements copied, which will be the minimum of
    // len(src) and len(dst).
    func copy(dst, src []Type) int

并且@Anonymous说编译器会跳过它: http://golang.org/src/cmd/go/build.go?#L558

       if p.Standard {
            switch p.ImportPath {

            case "builtin", "unsafe":
                // Fake packages - nothing to build.
            return a
            }

            // gccgo standard library is "fake" too.
            if _, ok := buildToolchain.(gccgoToolchain); ok {
                // the target name is needed for cgo.
                a.target = p.target
                return a
            }
        }