search instagram arrow-down

Archives

Categories

Meta

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.name, p.age)
}
func main() {
  alex := person{ name: "Alex", age: 18 }
  alex.print()
}

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 (
    "fmt"
    "math"
)
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){
    fmt.Println(s.area())
}
func main ()  {
    r:=rectangle {
        length:5.5,
        breadth:6.5,
    }
    c:=circle{radius:6.5}
    measure(r)
    measure(c)
}

Playground link: https://play.golang.org/p/GLllwqGWTYU

Interfaces are implemented implicitly.

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

References:
 https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go
https://gobyexample.com/interfaces
https://www.ardanlabs.com/blog/2014/05/methods-interfaces-and-embedded-types.html

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:

WordPress.com Logo

You are commenting using your WordPress.com 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: