2016-10-17 7 views
0

私は2つのパッケージ:offer.goとparser.goを持っています。構造体Dataの変数cartがあります。私は別のパッケージparserにある関数への引数として渡したいと思います。しかし私はそれをすることができません。以下に見てください。ただし、これを実行しているstruct型引数を別のパッケージの関数に渡すことができません

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) 
offer.go

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 
} 

、私は次のエラーを与える:

cannot use cart (type map[int]Data) as type map[int]Parser.Data in argument to Parser.BXATP 

私は、このリンクを見つけました解決策は私の場合は動作しないようです:

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

私はにパーサを変更します。

func BXATP(offer_id int, rule string, cart map[int]struct { 
    Id  int 
    Quantity int 
    Mrp  float64 
    Discount float64 
}, warehouseId int) 

しかし、今の誤差がある:

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 

私はこれを達成する方法を理解していません。どんな助けもありがとう。

答えて

1

Dataが2つのパッケージで定義されているのはなぜですか?まったく同じ構造が必要な場合は、1つのパッケージに入れてください。別々のパッケージで定義された

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) 

タイプは、彼らが名前と基本構造を共有している場合でも異なっている:あなたはparserでそれを残す場合は、あなたのような何かを行うことができます。したがってParser.Dataoffer.Dataと互換性がありません。

+0

私はタイプを使用していますが、 'Data'コードはに関連していないにも非常に多くの他の場所でのパッケージ提供でパーサ。 Parser Packageのオファーパッケージから 'Data'を使用する方法はありますか? – Jagrati

+0

循環インポートエラーが発生することはありません。 'offer 'はすでに' Parser'をインポートしているので 'Parser'に' offer'をインポートすることはできません。 1つの解決策は、型を第3のパッケージに移動し、それを 'offer 'と' Parser'の両方にインポートすることです。 – abhink

+0

また、 'offer'に' Data'を使用することもできます。 'offer'のどこにでも' Parser.Data'を使い、 'offer'から' Data'を削除するだけです。それらはまだ同じ構造ですので、型に定義されたメソッドがない限り、それは重要ではありません。 – abhink

0

あなたは別の構造体のフィールドにすべての単一の構造体のフィールドを割り当てる必要があり、例えば、以下を参照してください

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, 
    } 
} 
関連する問題