为什么我无法导入“内置”pkg?

问题描述 投票:0回答:2

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

go built-in
2个回答
5
投票

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

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

内置包提供了 Go 预先声明的文档 身份标识。此处记录的物品实际上并不在包装中 内置的,但它们的描述允许 godoc 呈现 该语言的特殊标识符的文档。

如果你看一下 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
            }
        }

4
投票

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

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

特别是,它不会搜索 .go 文件:假定这些文件已经构建。与 C++ 等相比,这对 Go 来说是一个巨大的胜利,因为每个包都可以编译一次,并且依赖于它的代码可以使用已经编译的版本。

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

© www.soinside.com 2019 - 2024. All rights reserved.