英文:
Call function from another file
问题
在main函数中正确调用unique函数的方法是使用包名作为前缀来调用函数。在你的代码中,unique函数位于main包中,因此你可以使用main.unique来调用它。以下是修改后的代码:
package main
import "fmt"
func unique(a []int) {
	var value int
	for i := range a {
		value = value ^ a[i]
	}
	fmt.Println(value)
}
func main() {
	var a = []int{1, 4, 2, 1, 3, 4, 2}
	main.unique(a[0:])
}
这样修改后,你应该能够正确调用unique函数了。
英文:
Inside my directory /go/src/lodo I have two files, main.go and uniqueElement.
uniqueElement.go
package main
import "fmt"
func unique(a []int) {
	var value int
	for i:= range a {
		value = value ^ a[i]
	}
	fmt.Println(value)
}
main.go
package main
func main() {
	var a = []int{1, 4, 2, 1, 3, 4, 2}
	unique(a[0:])
}
I get an error
./main.go:7: undefined: unique
How can I correctly call unique from main?
答案1
得分: 12
你可能是用go run main.go来运行你的代码,这只会编译并运行main.go。尝试运行go run main.go uniqueElement.go或者构建并运行生成的二进制文件。
英文:
You probably ran your code with go run main.go that only compiles and runs main.go try running go run main.go uniqueElement.go or building and running the binary generated
答案2
得分: 1
将名称从unique更改为Unique。
英文:
Change the name from unique to Unique.
答案3
得分: 1
以下是翻译好的内容:
以下代码对我有效:
//module github.com/go-restful/article
package article
func IndexPage(w http.ResponseWriter, r *http.Request) {}
这个函数必须是导出的,首字母大写,并添加注释
在 main.go 中的使用:
//module github.com/go-restful
package main
import (
	article "github.com/go-restful/article"
)
func handleRequests() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/", article.IndexPage)
}
英文:
The following codes work for me:
//module github.com/go-restful/article
package article
func IndexPage(w http.ResponseWriter, r *http.Request) {}
> This func must be Exported, Capitalized, and Comment added
The use in main.go
//module github.com/go-restful
package main
import (article "github.com/go-restful/article")
func handleRequests() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/", article.IndexPage)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论