duanke0555 2016-10-17 09:21
浏览 34
已采纳

无法将结构类型参数传递给另一个包中的函数

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:

Why passing struct to function with literal struct parameter from current package differs from the same for function from another package?

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.

  • 写回答

2条回答 默认 最新

  • dongzhou8764 2016-10-17 09:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号