Go - Interface 101

 

package main

import (
    "fmt"
)

// A 'class' struct for keeping Deployment data
type Deployment struct {
  Platform string
  Service string
}

// A method that acts on Deployment data
func (d Deployment) String() string {
  return fmt.Sprintf("Deployment: %s - %s", d.Platform, d.Service)
}

// An interface for things that have a String function
type StringifiableObject interface {
  String() string
}

// A function that can show StringifiableObjects
func show(s StringifiableObject) {
  fmt.Println(s.String())
}

func main() {
  // Create Deployment which has a String method
  d := Deployment{
    Platform: "Eschaton",
    Service: "alpha",
  }
  // Show the Deployment, which is a StringifiableObject
  show(d)
}

Comments

Popular Posts