简体   繁体   中英

Go + GoLand calling function in other file

Directory layout:

~ cd $GOPATH
~ tree src/simple 
src/simple
└── main
    ├── main.go
    └── other.go

main.go:

package main

import "fmt"

func main() {
    fmt.Println("This is in main. calling somefunc...")
    somefunc()
    fmt.Println("done. bye :)")
}

other.go:

package main

import "fmt"

func somefunc() {
    fmt.Println("This is in somefunc in other.go")
}

This works fine with go build :

~ cd $GOPATH/src/simple/main/
~ go build
~ ./main
This is in main. calling somefunc...
This is in somefunc in other.go
done. bye :)

From within the GoLand IDE, If I run, I get:

main/main.go:7:2: undefined: somefunc

Normally, there is editor highlighting of all syntax errors. The somefunc call is treated as valid syntax in the editor but when I run it doesn't work. I can even cmd-click into the function to jump to the definition.

This is with GoLand 2018.2.3 and go version go1.11

In GoLand create a Run Configuration Run -> Edit Configurations based on Go Build template and set

Name: Build (or whatever you like)
Run kind: Directory
Directory: /Users/gopher/go/src/simple/main/
                                      ^^^^^^
Run after build: checked
Working directory: /Users/gopher/go/src/simple

Change /Users/gopher/go/ part accordingly, to match your actual path of $GOPATH

And then Run -> Build the project

This is in main. calling somefunc...
This is in somefunc in other.go
done. bye :)

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM