Saturday 4 September 2021

Go Interface

 Go has different approaches to implement the concepts of object-orientation. Go does not have classes and inheritance. Go fulfill these requirements through its powerful interface.

Interfaces provide behavior to an object: if something can do this, then it can be used here.

An interface defines a set of abstract methods and does not contain any variable.

syntax:

  1. type Namer interface {  
  2.              Method1(param_list) return_type  
  3.              Method2(param_list) return_type  
  4.              ...  
  5. }  

where Namer is an interface type.

Generally, the name of an interface is formed by the method name plus the [e]r suffix, such as Printer, Reader, Writer, Logger, Converter, etc.

  • A type doesn't have to state explicitly that it implements an interface: interfaces are satisfied implicitly. Multiple types can implement the same interface.
  • A type that implements an interface can also have other functions.
  • A type can implement many interfaces.
  • An interface type can contain a reference to an instance of any of the types that implement the interface

Go Interface Example

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. type vehicle interface {  
  6.    accelerate()  
  7. }  
  8. func foo(v vehicle)  {  
  9.    fmt.Println(v)  
  10.      
  11. }  
  12. type car struct {  
  13.    model string  
  14.    color string  
  15. }  
  16. func (c car) accelerate()  {  
  17.    fmt.Println("Accelrating?")  
  18.      
  19. }  
  20. type toyota struct {  
  21.   model string  
  22.    color string  
  23.    speed int  
  24. }  
  25. func (t toyota) accelerate(){  
  26.    fmt.Println("I am toyota, I accelerate fast?")  
  27. }  
  28. func main() {  
  29.    c1 := car{"suzuki","blue"}  
  30.    t1:= toyota{"Toyota","Red"100}  
  31.    c1.accelerate()  
  32.    t1.accelerate()  
  33.    foo(c1)  
  34.    foo(t1)  
  35. }  

Output:

Accelrating...
I am toyota, I accelerate fast...
{suzuki blue}
{Toyota Red 100}

No comments:

Post a Comment