2 回答

TA貢獻1829條經驗 獲得超6個贊
問題是您有兩個單獨的person定義。不要在 main 中重新聲明它,而是使用 package 中的那個function。
package functions
import "fmt"
type Person struct {
Name string
Age int
}
func Hello(p Person) {
fmt.Println(p.name, "is", p.age, "years old")
}
將 Person 更改為大寫字母,并將其用于導出的字段。
package main
import (
"./functions"
)
func main() {
person1 := functions.Person{"James", 24}
functions.Hello(person1)
}

TA貢獻1856條經驗 獲得超5個贊
您正在定義兩種不同的結構類型(具有相同的字段,但不同) - 其中一種是person,另一種是調用functions.person。
在這種情況下,正確的方法是functions/functions.go像這樣定義你的結構:
package functions
import "fmt"
// Use uppercase names to export struct and fields (export == public)
type Person struct {
Name string
Age int
}
func Hello(p Person) {
fmt.Println(p.Name, "is", p.Age, "years old")
}
現在main.go,您可以導入包functions并訪問其導出/公共結構:
package main
import (
"./functions"
)
// No need to redeclare the struct, it's already defined in the imported package
func main() {
// create an object of struct Person from the functions package. Since its fields are public, we can set them here
person1 := functions.Person{"James", 24}
// call the Hello method from the functions package with an object of type functions.Person
functions.Hello(person1)
}
關鍵的一點是,使用相同名稱定義的結構不會自動相同,即使它們看起來很相似——畢竟它們的定義不同。
如果兩個結構具有相同的字段,您也可以進行類型轉換,但這是另一回事。
- 2 回答
- 0 關注
- 122 瀏覽
添加回答
舉報