Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
interfaces

How to use Interfaces in GO

Educative Answers Team

Interfaces

Interfaces are collections of method signatures. Method signatures in GO declare the name and parameter types, and return types of methods in interfaces.

Usage

The example below shows the declaration of a very basic interface.

type shape interface {
    area() float64
    perimeter() float64
}

This code defines the interface for shapes and declares two functions, area() and perimeter() with the return type of float64.

package main

import "fmt"

//Interface declaration
type shape interface {
    area() float64
    perimeter() float64
}
//Struct declaration for rectangle
type rectangle struct{
  length, height float64
}
//Struct declaration for circle
type circle struct{
  radius float64
}
//Method declarations for rectangle
func (r rectangle) area() float64 {
    return r.length * r.height
}
func (r rectangle) perimeter() float64 {
    return 2 * r.length + 2 * r.height
}
//Method declarations for circle
func (c circle) area() float64 {
    return 3.142 * c.radius * c.radius
}
func (c circle) perimeter() float64 {
    return 2 * 3.142 * c.radius
}

func main() {
    r := rectangle{length: 10.0, height: 5.0}
    c := circle{radius: 5.0}

    fmt.Println("Area of rectangle is ", r.area())
    fmt.Println("Parameter of rectangle is ", r.perimeter())
    fmt.Println("Area of circle is ", c.area())
    fmt.Println("Perimeter of circle is ", c.perimeter())

}

This piece of code defines an interface, shape, and two structs that implement this interface, rectangle and circle. Variables of these two structs are declared in the main function. These variables use the functions, area() and perimeter(), declared in the interface. They start on lines 19 and 26 for the rectangle and circle, respectively.

RELATED TAGS

golang
interfaces
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring