Referencing a method from one file to another in GO language

huangapple go评论78阅读模式
英文:

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()
}

huangapple
  • 本文由 发表于 2014年8月22日 15:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/25441611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定