Rafiq
Rafiq

Reputation: 51

Go structure as method receiver with and without interface

I am new to Go. Want to know what is benefit or drawback when struct act as receiver of method with OR with out interface

type DB struct

func (db *DB) add(user User) {...//some code }
func (db *DB) remove(user User) {..//some code}

type UserAccess inferface {
    func add(user User)
    func remove(user User)
}

func (db *DB) add(user User) {...//some code }
func (db *DB) remove(user User) {..//some code}

PLEASE NOTE: above example is JUST to put thing in code.

I am asking this as, I have seen many Go library code in github which use empty struct as method receivers.

I know almost all blogs and go-guru bit a drum of using interface.

But which are the places, where interface actually needed in go lang implementation? and what we loss or gain because of that?

Upvotes: 0

Views: 784

Answers (1)

sberry
sberry

Reputation: 132018

In your first example, a DB or pointer to DB can act as the receiver. In your second example, using an interface, you can still only have a DB or &DB as the receiver, but nobody else has to know that (assuming you capitalized your function names to Add and Remove). Instead, you would be able to use a UserAccess interface which could be a DB or &DB, but could be anything else that implemented the Add and Remove functions.

This is really helpful for a couple reasons. First, this is way more testable as you can use something the implements the UserAccess interface but never touches a database. As long as the thing your are testing has the two functions with matching signatures it can be used instead. There are mocking libraries that take advantage of this to autogenerate code.

Secondly, if you use an interface then your caller doesn't need to know anything about the actual type (DB in this case) and it will only have access to the functions defined on the interface instead of the entire API of your type.

There is lots of other good reading material out there for the benefits and design considerations behind interfaces.

Upvotes: 1

Related Questions