Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a struct to another package?

Tags:

go

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.

like image 262
Peter Avatar asked Sep 21 '25 01:09

Peter


1 Answers

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)
}
like image 103
peterSO Avatar answered Sep 22 '25 23:09

peterSO