Quick actions

cmd+k|ctrl+k

Navigation

Languages

Go - Using interfaces

Snippet info

Language

Go

Visibility

public

Author

klassmann

Created

2018-03-21T18:11:31Z

Updated

2018-03-21T18:16:03Z

// Example of using interface
// Author: http://github.com/klassmann
package main

import (
    "fmt"
)

type Runner interface {
    Execute() bool
}


type Job struct {
    Data string
    IsRunning bool
}

func (j Job) Execute() bool {
    fmt.Printf("Executing Job[%s]...", j.Data)
    return j.IsRunning
}

type Task struct {
    Name string
}

func (t Task) Execute() bool {
    fmt.Printf("The Task[%s] is executing...", t.Name)
    return true
}

// Using inteface, you can pass any type that implements a method
// like Execute() bool, it is called "implicity implementation"
// https://tour.golang.org/methods/10
func runProcess(r Runner) {
    if r.Execute() {
        fmt.Printf("Done.\n")
    } else {
        fmt.Printf("Fail.\n")
    }
}


func main() {
    
    fmt.Println("Job and Task processor!")
    j1 := Job {Data: "Job 1", IsRunning: true}
    j2 := Job {Data: "Job 2", IsRunning: false}
    j3 := Job {Data: "Job 3", IsRunning: true}
    
    t1 := Task {Name: "Task 1"}
    t2 := Task {Name: "Task 2"}
    t3 := Task {Name: "Task 3"}
    
    runProcess(j1)
    runProcess(j2)
    runProcess(j3)
    runProcess(t1)
    runProcess(t2)
    runProcess(t3)
}
INFO