2016-12-31 9 views
0

私は私のAPIで使用したいモデルのための汎用インターフェースをgoで作成しようとしています。CRUDモデル用の汎用インターフェイスを作成する方法は?

type Model interface { 
    Create(interface{}) (int64, error) 
    Update(string, interface{}) (error) 
} 

そして、私はそれを実装していpersonModelている:私はPersonModelModelを実装していないどのように関連するエラーを取得していますしかし、私は、仕事にこれを

type Person struct { 
    Id int `json:"id"` 
    FirstName string `json:"firstName"` 
} 

type PersonModel struct { 
    Db *sql.DB 
} 

func (model *PersonModel) Create(personStruct person) (int64, error) { 
    // do database related stuff to create the person from the struct 
} 

func (model *PersonModel) Update(id string, personStruct person) (error) { 
    // do database related stuff to update the person model from the struct 
} 

を取得することはできませんインタフェース。

私の主な目標は、コントローラで使用できるアプリケーション内のすべてのモデル(createおよびupdateの実装)の統一されたインターフェイスを持つことです。どうすればこの問題を克服できますか?

+1

方法は、作成および更新がないパラメータとして空のインターフェイスを{}必要人の構造 –

答えて

1

あなたはこのようなあなたのメソッドを実装しようとする必要があり、それはあなたがあなたのFUNCに尋ねるというだけの理由だのparamsとして空のインターフェイスを作成し、更新します。

func (model *PersonModel) Create(v interface{}) (int64, error) { 
    // do database related stuff to create the person from the struct 
} 

func (model *PersonModel) Update(id string, v interface{}) (error) { 
    // do database related stuff to update the person model from the struct 
} 
関連する問題