繁体   English   中英

Go + GoLand调用其他文件中的函数

[英]Go + GoLand calling function in other file

目录布局:

~ 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

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

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/ part,以匹配$GOPATH实际路径

然后Run -> Build项目

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

Process finished with exit code 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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