如何将一个包的结构分配给具有相同字段的另一个包的结构

I have a struct in main package :

package main
type DispatchesDetailsStruct struct{}

And I created another struct in package store With same fields as of struct created in main package.

package store
type DispatchesDetails struct{}

Here what I'm going to do, I created a function inside store package with return DispatchesDetails struct.

func (s *DispatchStore) GetDispatchByCondition(dispatchObject DispatchesRequestStruct, objRaouteAvailability Availability) (dds []DispatchesDetails, err error) {}

Now i call this store function from main package and assign returned value to main package struct but its showing error message

can not assign store.DispatchesDetails to DispatchesDetailsStruct type.

I'm confused please help me. Thanks

You need to import store package inside your main package. Go is strictly typed language. Here you cannot assign a struct to another struct even if they are similar. Though you can embed your struct into another.

package main
import( 
      "store"
     )

type DispatchesDetailsStruct struct{

}

func main(){
  storedispatchObject := store.DispatchesDetailsStruct{}
  storedispatchObject.value = userDetails.value
  dispatchesList, err := dps.GetDispatchByCondition(storedispatchObject, objRaouteAvailability)
}

After above code snippet the DispatchesDetailsStruct will be of store type and you can use it in store function

main.DispatchesDetails and store.DispatchesDetails are completely different types. You probably want to choose one and use it exclusively.

For example, instead of:

package main

details := &DispatchesDetails{ ... }

use:

package main

details := &store.DispatchesDetails{ ... }

Go considers named types different even they have the same structure.

I recommend this way if you need the same type in different structures - move all types definitions to 3rd package and import from there.

Thus you solve many issues at once:

  1. Every type is defined once. If you need some changes you do them in one place.

  2. All definitions are grouped together - easier to find. Package with types will be small.

  3. You never run into cyclic imports if you need type from another package.

So you may come to a project structure like this:

github.com/user/project/schema  — types
github.com/user/project/user  — some package for users
github.com/user/project/resources  — types