search instagram arrow-down




Methods and Interfaces in Go

Go has both methods and functions. In Go, a method is a function that is declared with a receiver. A receiver is a value or a pointer of a named or struct type. All the methods for a given type belong to the type’s method set.

package main
import "fmt"
type person struct {
   name string
   age int
func (p person) print() {
   fmt.Printf("%s is of %d years \n",, p.age)
func main() {
  alex := person{ name: "Alex", age: 18 }

More precisely, the print() function is a function which can receive a person. Another example can be a Notify() function which can receive a User.

type User struct {
    Name string
    Email string
func (u User) Notify() error

Interfaces in Go is two things. It is a set of methods but it is also a type. these methods do not contain codes. Apart they are not implemented (they are abstract). An interface can be declared in the format:

type Namer interface {
          Method1 (param_list) return_type
          Method2 (param_list) return_type 

Generally the name of the interface is formed by the method name plus [e]r suffice such as Reader and Printer.

Example of an Interface:

package main
import (
type shaper interface {
    area() float64

type rectangle struct {
    length float64
    breadth float64
type circle struct {
    radius float64
func (r rectangle) area() float64 {
    return r.length * r.breadth
func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
func measure(s shaper){
func main ()  {
    r:=rectangle {

Playground link:

Interfaces are implemented implicitly.

Interface Jokes: Hey babe, if you have any methods of mine, then you are of my type.


Leave a Reply
Your email address will not be published. Required fields are marked *

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: