0

I'm trying to create a generic interface in go for models I wish to use in my api.

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

And I have a personModel which implements it:

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
}

However, I can't get this to work, as I'm getting errors related to how the PersonModel does not implement the Model interface.

My main goal is to have a unified interface for all models in my application (implementing create and update) that can be used by the controllers. How would I go about overcoming this problem?

1
  • 1
    methods Create and Update need an empty interface{} as parameters no a person struct Commented Dec 31, 2016 at 21:28

1 Answer 1

1

You should try to implement your method like this, it's just because you ask in your func Create and Update an empty interface as 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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.