2015-10-04 63 views
3

我有一些Golang問題並且包含了包裹。我有scructureGolang進口配套包

src/ 
├── hello_world 
│   ├── hello.go 
│   └── math 
│    └── add.go 

hello.go文件包含以下代碼:

package main 

import (
    "fmt" 
    math "hello_world/math" 
) 

func main() { 
    fmt.Println("Hello World") 
    x := math.add(6, 5) 
} 

add.go

package math 

func add(x, y int) int { 
    return x + y 
} 

當我做go run hello go我看到:

[email protected]:~/go/src/hello_world$ go run hello.go 
# command-line-arguments 
./hello.go:10: cannot refer to unexported name math.add 
./hello.go:10: undefined: "hello_world/math".add 

GOPATH

[email protected]:~/go/src/hello_world$ echo $GOPATH 
/home/evgen/go 

如何解決?謝謝!

回答

9

在軟件包的外面,只有導出的標識符可以被訪問和引用,即以大寫字母開頭的標識符。

因此最簡單的解決方法是通過改變它的名字導出math.add()功能Add()math.go

func Add(x, y int) int { 
    return x + y 
} 

,當然,當你從main.go引用它:

x := math.Add(6, 5) 

另外,請注意,導入hello_world/math包時,您不必指定新名稱來引用其導出的標識符:默認情況下它將是其最後一部分的進口路徑,所以這是等同於您的進口:

import (
    "fmt" 
    "hello_world/math" 
) 
+0

哈!我真笨!非常感謝你! –

0

,並要求當添加在你的主要功能,不使用這個

x := math.Add(6 + 5) 

而是使用

x := math.Add(6, 5) 
+0

你可以編輯其他用戶的答案,而不是發佈一個新的答案,糾正另一個 – saniales

0

功能,變量,來自不同包的任何東西都必須以大寫字母開頭,以便在導入主包時使其可見。

例如:

package main 

import "fmt" 
import "other/out" 

func main(){ 

fmt.Println(out.X) 

// hello 

} 
package other 

var X string = "hi" 
2

大寫要等功能來讀取你的包內的功能:

func Add(x, y int) int { 
     return x + y 
} 

然後調用它在hello.go這樣:

x := math.Add(6, 5) 

保持它們的小寫確實有它的目的,特別是如果你想保護它避免在包裹外意外使用。