如何将一个结构体传递给另一个包?

huangapple go评论78阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2013年8月21日 07:15:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/18346432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定