I have two packages: offer.go and parser.go. I have a variable cart
of type struct Data
. I want to pass it as an argument to a function which is in another package parser
. However I am not able to do that. Please look into the following:
offer.go
package offer
import "go_tests/Parser"
type Data struct {
Id int
Quantity int
Mrp float64
Discount float64
}
cart := make(map[int]Data)
//cart has some data in it
//passing it to parser
Parser.BXATP(offer_id, rule.Description, cart, warehouseId)
parser.go
package Parser
type Data struct {
Id int
Quantity int
Mrp float64
Discount float64
}
func BXATP(offer_id int, rule string, cart map[int]Data, warehouseId int){
//my code is here
}
However running this, gives me following error:
cannot use cart (type map[int]Data) as type map[int]Parser.Data in argument to Parser.BXATP
I found this link but the solution doesn't seem to work in my case:
I change the parser to :
func BXATP(offer_id int, rule string, cart map[int]struct {
Id int
Quantity int
Mrp float64
Discount float64
}, warehouseId int)
But now error is :
cannot use cart (type map[int]Data) as type map[int]struct { Id int; Quantity int; Mrp float64; Discount float64 } in argument to Parser.BXATP
I don't understand how to achieve this. Any help will be appreciated.
Why do you have Data
defined in two packages? If you need the exact same structure, just have it in one package. If you leave it in parser
, you can do something like:
package offer
import "go_tests/Parser"
cart := make(map[int]Parser.Data)
//cart has some data in it
//passing it to parser
Parser.BXATP(offer_id, rule.Description, cart, warehouseId)
Types defined in separate packages are different even if they share name and underlying structure. So Parser.Data
is not compatible with offer.Data
.
You need to assign every single struct field to another struct field, see example:
package parser
import "./offer"
type Data struct {
Id int
Quantity int
Mrp float64
Discount float64
}
func main(){
offer_data := &offer.Data{}
parser_data := &Data{
Id: offer_data.Id,
Quantity: offer_data.Quantity,
Mrp: offer_data.Mrp,
Discount: offer_data.Discount,
}
}