英文:
How to pass a struct to another package?
问题
这是一个非常简化的版本,我正在尝试做的事情,请帮我处理以下情况:
PackageA.go
package A
import "B"
type TestStruct struct {
Atest string
}
func Test() {
test := TestStruct{"Hello World"}
B.Test(test)
}
PackageB.go
package B
import "fmt"
func Test(test TestStruct) {
fmt.Println(test.Atest)
}
当它到达Package B时,会出现undefined: test
的错误。
基本上,我在将结构体从一个包传递到另一个包时遇到了问题,甚至无法传递作为指向其他结构体或函数的指针的变量。
任何指针都将非常有帮助。
英文:
This is a very watered down version of what I'm trying to do but please help me with the following scenario:
PackageA.go
package A
import "B"
type TestStruct struct {
Atest string
}
func Test() {
test := TestStruct{"Hello World"}
B.Test(test)
}
PackageB.go
package B
import "fmt"
func Test(test TestStruct) {
fmt.Println(test.Atest)
}
This fails with undefined: test
when it hits Package B
Basically I'm having issues passing structs from one package to another or even passing variables that act as pointers to other structs or functions.
Any pointers would be very helpful.
答案1
得分: 9
重新组织你的代码如下:
a.go
package a
import "b"
func Test() {
test := b.TestStruct{"Hello World"}
b.Test(test)
}
b.go
package b
import "fmt"
type TestStruct struct {
Atest string
}
func Test(test TestStruct) {
fmt.Println(test.Atest)
}
英文:
Reorganize your code as:
a.go
package a
import "b"
func Test() {
test := b.TestStruct{"Hello World"}
b.Test(test)
}
b.go
package b
import "fmt"
type TestStruct struct {
Atest string
}
func Test(test TestStruct) {
fmt.Println(test.Atest)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论