Go:从库中调用函数

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

Go: Function call from a library

问题

现在我真的很困惑。这是我的问题(对于Go语言,我还不熟悉):

第一个文件:

// main.go
package main

import "./libraries/test"

func main() {

    test.foo()
}

第二个文件:

// test.go
package test

import "fmt"

func foo() {

    fmt.Println("foo")
}

我的结构如下:

main.go
   /libraries
        /test
           test.go

如果我编译这段代码,我会得到以下错误信息:

> ./main.go:7: 无法引用未导出的名称 test.foo
>
> ./main.go:7: 未定义: test.foo

如果我将foo改为Foo,错误就消失了,程序按预期工作。

英文:

Now I'm really confused. Here is my problem (Go is new to me):

Firs file:

// main.go
package main

import "./libraries/test"

func main() {

    test.foo()
}

Second file:

// test.go
package test

import "fmt"

func foo() {

    fmt.Println("foo")
}

My structure looks like this:

main.go
   /libraries
        /test
           test.go

If I compile this code I'll get this error messages:

> ./main.go:7: cannot refer to unexported name test.foo
>
> ./main.go:7: undefined: test.foo

If I change foo to Foo everywhere the error is gone and the program works as expected.

答案1

得分: 3

我猜你没有仔细阅读Go文档。所有以大写字母开头的名称都是从它们所在的包中导出的。所有小写字母开头的名称都不会被导出。

英文:

I suppose that you have not read the Go docs very closely. All names which begin with capital letters are exported from their package. All names in lowercase are not exported.

答案2

得分: 3

在Go语言中,一个符号的名称是使用大驼峰命名法还是小驼峰命名法是非常重要的区别。这不仅适用于函数,还适用于类型(如结构体或接口)以及结构体成员。

你可以在Go文档中找到相关信息(重点是我的):

在Go语言中,名称和其他语言一样重要。它们甚至具有语义效果:一个名称在包外的可见性取决于它的首字母是否大写

这意味着你不能随意命名函数和类型。如果你需要从另一个模块调用该函数,它必须被命名为Foo,而不是foo

英文:

In Go, it's an important distinction whether a symbol's name is written in upper or lower camel case. This goes for functions, but also for types (like structs or interfaces) and also struct members.

You can read this up in the Go documentation (emphasis mine):

>Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case.

This means that you cannot name functions and types arbitrarily. If you need to call this function from another module, it must be named Foo, and not foo.

huangapple
  • 本文由 发表于 2015年12月21日 03:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/34384648.html
匿名

发表评论

匿名网友

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

确定