Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I import pkg "builtin"?

Tags:

go

built-in

cat test.go

package main

import "builtin"

func main() {
    return
}

go run test.go

can't find import: "builtin"

I'm just curious because the file exists and is properly packaged. But can't be imported like other packages.

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

like image 728
tuxcanfly Avatar asked Jun 02 '14 12:06

tuxcanfly


2 Answers

You don't need to import it. Is imported by default.

From 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. 

from golang.org/pkg/builtin)

If you take a look at the content of http://golang.org/src/pkg/builtin/builtin.go You will notice that there are only declarations

    // 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

and as @Anonymous says the compiler skips it: 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
            }
        }
like image 57
fabrizioM Avatar answered Nov 04 '22 21:11

fabrizioM


When you import a package, the compiler (or at least, the gc compiler), searches for the already compiled package.

You can see this code in the source: http://golang.org/src/cmd/gc/lex.c?#L578

In particular, it doesn't search for .go files: these are assumed to be already built. This is a big win for go compared to, for example, C++, because each package can be compiled once, and code that depends on it can use the already-compiled version.

So why doesn't "builtin" ever get built, even though it's there as a package? Well, it's special-cased to be ignored in the part of the code that builds dependencies before building a source file: http://golang.org/src/cmd/go/build.go?#L558

like image 4
Paul Hankin Avatar answered Nov 04 '22 19:11

Paul Hankin