Provide Best Programming Tutorials

How Golang implements interface

It is very simple to define and implement interfaces in Golang.
Let me use an example to help you understand.
Suppose we have an interface called DB. This interface contains general methods of the database, such as adding, deleting, modifying, and checking data.

type DB interface {

Then you can create a concrete instance called Mysql to implement this interface.

type Mysql struct {

Then you just need to implement all the methods defined in DB interface , but these methods should bound to Mysql instance.

func (mysql Mysql) addData() {
	println("mysql implement add data method")
func (mysql Mysql) queryData() {
	println("mysql implement query data method")
func (mysql Mysql) updateData() {
	println("mysql implement update data method")

func (mysql Mysql) deleteData() {
	println("mysql implement delete data method")

And done!

Next, you can test it :

func main(){
  var mysql Mysql
  var db DB = mysql

Very simple, is it? Unlike another programming language like Java in which you should using keyword implements display which interface the current class should implement.

Leave a Reply

Close Menu