golang“未定义”函数在另一个文件中声明? [英] golang "undefined" function declared in another file?

查看:1262
本文介绍了golang“未定义”函数在另一个文件中声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个基本的go程序,用于在不同的文件上调用函数,但是是同一个软件包的一部分。但是,它返回:

  undefined:NewEmployee 

以下是源代码:

main.go

  package main 

func main(){
emp:= NewEmployee()

$ / code>

employee.go

 包主

类型雇员结构{
名称字符串
年龄int

$ b $ func NewEmployee()* Employee {
p:=& Employee {}
return p
}

func PrintEmployee(p * Employee){
returnHello world!
}

预先致谢

解决方案

请阅读如何编写转码

不要在 GOPATH 中使用 / src 。包位于 $ GOPATH / src



对于 build install 您需要将文件放在软件包目录中。


$ b $

对于 go run ,您需要提供所有文件作为参数:

  go run main.go employee.go 



<但是,你应该几乎总是使用 go install go build (最好是前者,如 go build 在使用非主包时会导致混淆)


I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:

undefined: NewEmployee

Here is the source code:

main.go:

package main

func main() {
emp := NewEmployee()    
}

employee.go:

package main

type Employee struct {
    name string
    age int
}   

func NewEmployee() *Employee {
    p := &Employee{}
    return p
}

func PrintEmployee (p *Employee)  {
    return "Hello world!"
}

Thanks in advance

解决方案

Please read "How to Write Go Code".

Don't use /src in your GOPATH. Packages are located in $GOPATH/src.

For build or install you need to have your files in a package directory.

For go run, you need to supply all files as argument:

go run main.go employee.go

But, you should almost always use go install, or go build (and preferably the former, as go build causes confusion when working with non-main packages)

这篇关于golang“未定义”函数在另一个文件中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆