2013-12-09 89 views
4

如果我運行下面的代碼一切編譯和運行良好:進口結構方法不靈

package main 

import "fmt" 

type Point struct { 
    x, y int 
} 

func (p *Point) init() bool { 
    p.x = 5 
    p.y = 10 
    return true 
} 

func main() { 
    point := Point{} 
    point.init() 
    fmt.Println(point) 
} 

但是當我移動Point struct一個包在$GOPATH目錄,然後我得到以下錯誤:point.init undefined (cannot refer to unexported field or method class.(*Point)."".init)

任何人都可以向我解釋爲什麼會發生這種情況?

一旦我把Point struct一個叫class的代碼如下包(誤差是8號線在那裏我稱之爲init法):

package main 

import "fmt" 
import "class" 

func main() { 
    point := class.Point{} 
    point.init() 
    fmt.Println(point) 
} 
+1

這是習慣寫一個函數'NewPoint'構建各種參數,而不是調用點'之後啓動。 – nemo

+0

真的,但我使用RPC包,它只允許註冊一個對象,所以我不得不將init作爲方法 – Tom

回答

11

重命名初始化()到初始化()應該工作!
基本上,所有不以Unicode大寫字母開頭的東西(函數,方法,結構體,變量)只會在它們的包中可見!

您需要閱讀從語言規範在這裏更多: ​​

相關位:

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported.
+2

酷,這是一個比我更好的來源,但你應該總是包含相關的引用因爲鏈接可能會失效 – Tom