Search code examples
goimportpackageprogram-entry-point

Importing "main" package as a library (According to _The Go Programming Language_)


On page 308 of The Go Programming Language, it says

A package named main ordinarily produces an executable program, but it can be imported as a library too.

But when I try it, I get an error: imp.go:5:5: import "foo" is a program, not an importable package

So...what are they talking about? How can you import a main package as a library?

My trial code is just:

imp.go

package main

import (
    "fmt"
    "foo"
)

func main() {
    fmt.Println(foo.Hi)
}

foo/foo.go

package main

import "fmt"

var Hi int = 3

func main() {
    fmt.Printf("Hi %d!\n", Hi)
}

Solution

  • Relevant: Access main package from other package

    My best guess is that this was true when the book was written, but has since been made impossible. golang/go#4210 is the relevant issue and it seems the change that stopped it from working landed in mid-2015 while the book was published only a few months after.