2016-09-26 49 views
2

很抱歉,如果這是一個有點基本的,我想從另一個包導入結構中轉到以下文件如何從外包裝訪問結構圍棋

// main.go 
import "path/to/models/product"  
product = Product{Name: "Shoes"} 

// models/product.go 
type Product struct{ 
Name string 
} 

但在主。產品結構未定義? 如何導入結構

+0

可能只是一個不完整的例子,但'產品= {產品名稱:「鞋」}'是不是一個有效的語句,這樣你可能會被誤解的錯誤。您需要在該分配中使用':=',因爲'product'先前未被聲明。 – evanmcdonnal

回答

5

在你去導入「完整」,而不是包的功能或類型。
(詳情請參見此相關的問題:What's C++'s `using` equivalent in golang

的語法和關鍵字import和進口報關的更深層次的解釋見Spec: Import declarations

一旦你導入了一個包,你可以參考它的exported identifiersqualified identifiers,它的格式爲:packageName.Identifier

所以,你的例子看起來是這樣的:

import "path/to/models/product" 
import "fmt" 

func main() { 
    p := product.Product{Name: "Shoes"} 
    // Use product, e.g. print it: 
    fmt.Println(p) // This requires `import "fmt"` 
} 
+0

如果我在導入前使用'.'導入模型文件夾,並在以下方法中使用結構體'Post':func(p * Post)All(){fmt.Println(「foo」)}'它仍然顯示未定義雖然? –

+1

@ColleenLarsen建議不要使用「點導入」(僅用於測試目的),因爲它是否有效取決於您如何以及從何處嘗試編譯/運行代碼。 – icza

+0

確定使用相同的方法刪除導入上的'.'作爲'func(p * models.Post)''models'由於某種原因未定義? –