英文:
Referencing a method from one file to another in GO language
问题
我正在学习Go语言,出于自己的兴趣。我来自一个典型的面向对象编程背景。
我在使用一个文件中的方法时遇到了一些困难。所以,D:\lib\pac\abc.go
中有一个名为dosomething
的方法。
现在,我在同一位置创建了另一个文件def.go
。在这个文件中,我正在编写一个函数来调用abc.go
,但是当我使用$ go test
运行这个文件时,我得到一个名为"undefined:dosomething"的异常。
这两个文件都在同一个包中。对于这个问题有什么提示吗?
英文:
I am learning Go language out of my own interest . I come from a typical OO programming .
I am bit kind of stuck in using a method present in one file from another.
So , D:\lib\pac\abc.go
has a method called
func dosomething()
{
}
Now , I have created one more file called def.go in the same location
In this file I am writing to function to call abc.go, but I am getting an exception called "undefined:dosomething" when I run this file using $ go test
func defFunc()
{
//call dosomething
}
Also both these files are in the same package. Any hint on this issue?
答案1
得分: 8
请阅读 http://golang.org/doc/code.html 并正确设置你的GOPATH工作空间。
一旦你完成了这个步骤,一个Go包中的所有文件都可以访问该包中任何文件中声明的符号,这样就不会出现任何问题。
英文:
Please read http://golang.org/doc/code.html and setup your GOPATH workspace correctly.
Once you've done this there should be no issue as all files in a single Go package are able to access symbols declared in any file in the package.
答案2
得分: 4
开始于http://tour.golang.org/和其他golang.org上的文档,这是初学者的起点。
在你的例子中,我看到你把大括号放在了下一行,这是一个错误,因为编译器会自动插入分号,将你的代码转换成:
func dosomething(); // 错误
{
// 与dosomething()无关的自己作用域的代码
}
英文:
Start with http://tour.golang.org/ and other documentation for starters on golang.org.
In your example I see that you have your braces on the next line, which is an error, because the compiler inserts semicolons automatically, turning your code into
func dosomething(); // error
{
// code in its own scope that has nothing to do with dosomething()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论