Learn Golang
  • Learn Go
  • The Basics
    • Installing Go
    • Hello World
  • Language Features
    • Basic Input Output
    • Variable Basics
    • Control Statements
    • Loops
    • Functions
    • Recursion
  • Data Structures
    • Arrays
    • Slices
    • Maps
    • Pointers
    • Structs
  • Other Concepts
    • Sorting
    • Interfaces
    • Generics
    • Goroutines
  • References
Powered by GitBook
On this page
  1. Other Concepts

Interfaces

PreviousSortingNextGenerics

Last updated 2 years ago

CtrlK

In golang, an interface is essentially a method signature on a struct. That is, Interfaces are named collections of method signatures, and a variable of interface type can hold any value that implements these methods. Here's how that works

package main

import "fmt"

// decleare a struct called Planet
type Planet struct {
  radius float64
  gravitation_constant float64
  mass float64
}
// define the interface
// in a planetary system, we can calculate the gravitational
// force the planet exerts on a given object with mass
type PlanetSystem interface {
  gravitational_force(mass float64) float64
}

// define the interface method
func (p Planet) gravitational_force(object_mass float64) float64 {
  F := (p.gravitation_constant * p.mass * object_mass) / (p.radius * p.radius)
  return F
}

// make use of the interface
func weight_on_planet(planet PlanetSystem, mass float64) float64 {
  return planet.gravitational_force(mass)
}

func main() {
  earth := Planet{radius: 6371, gravitation_constant: 6.67e-11, mass: 5.972e24}
  fmt.Println(weight_on_planet(earth, 80))
}