其他文件中的Go + GoLand调用功能

时间:2018-09-30 02:34:56

标签: go goland

目录布局:

~ 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")
}

这可以与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 :)

在GoLand IDE中,如果运行,我将得到:

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

通常,编辑器会突出显示所有语法错误。 somefunc调用在编辑器中被视为有效语法,但是在我运行时不起作用。我什至可以cmd单击该函数以跳到定义。

这与GoLand 2018.2.3和go version go1.11

1 个答案:

答案 0 :(得分:2)

在GoLand中,基于Run -> Edit Configurations模板创建运行配置Go Build并进行设置

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

相应地更改/Users/gopher/go/部分,以匹配您的$GOPATH的实际路径

然后Run -> Build个项目

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

Process finished with exit code 0