gpt4 book ai didi

Go + Go Lang 在另一个文件中调用函数

转载 作者:IT王子 更新时间:2023-10-29 01:56:47 24 4
gpt4 key购买 nike

目录布局:

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

其他.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-click 进入函数以跳转到定义。

这是 GoLand 2018.2.3 和 go version go1.11

最佳答案

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

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

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

然后Run -> Build 项目

This is in main. calling somefunc...This is in somefunc in other.godone. bye :)Process finished with exit code 0

关于Go + Go Lang 在另一个文件中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com