如何从Golang中的相邻文件导入代码

Ah yes, the canonical problem when learning a new programming language. I have this:

$GOPATH/
   src/
     huru/
       foo/
          side.go
       hello.go

in hello.go I have:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)


func main(){
   Foo()
}

and in foo/side.go, I have:

package main

func Foo() {

}

I run:

go install huru

and I get:

# huru
src/huru/hello.go:22:2: undefined: Foo

the compiler doesn't like the Foo() call in hello.go, how do I import it properly? Should I be using package main for both files? Why wouldn't the package be called huru, I assume I should call the package huru..instead of main? idk.

You must not use main as the package name of huru/foo/side.go, because it's already used in the huru/hello.go where the path is different than where side.go located.

So change the package name on the huru/foo/side.go file. Better to use folder name as the package name.

package foo

func Foo() {

}

Then on the huru/hello.go, import the huru/foo package so you'll be able to consume the Foo() function that defined on the file inside.

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "huru/foo" // <------ here
)

func main(){
   foo.Foo()
}

As described in the Go Documentation, a program is defined by a single unimported main package. You can't have multiple main packages in a program, so if you want to make a library, e.g. your foo dir, you need to define a different package name.

Also included in the documentation is a description for how imports are handled. To be fair, it's a bit cryptic and they don't explicitly mention $GOPATH, but imports are taken relative to it. You can't import a package relative to a specific file, however.

Your code will compile fine if you do something like this:

hello.go:

package main

import . "huru/foo"

func main() {
        Foo()
}

foo/side.go:

package foo

import "fmt"

func Foo() {
        fmt.Println("Hello from side.go");
}