Skip to content

Instantly share code, notes, and snippets.

@ynwd
Last active November 26, 2020 03:35
Show Gist options
  • Save ynwd/ccd907c33ed90c35b7642c1b219ac293 to your computer and use it in GitHub Desktop.
Save ynwd/ccd907c33ed90c35b7642c1b219ac293 to your computer and use it in GitHub Desktop.
Super Easy Golang Interface Explanation

Interface dan Class

Konteks tulisan ini bisa dilihat di page sebelumnya:

Misalkan ada interface dan class seperti ini di TypeScript:

interface ClockInterface {
  currentTime: Date;
  setTime(d: Date): void;
  getTime(): Date;
}

class Clock implements ClockInterface {
  currentTime: Date = new Date();
  setTime(d: Date) {
    this.currentTime = d;
  }
  getTime() {
      return this.currentTime;
  }
}

const c = new Clock();
console.log(c);

Yang jadi pertanyaan:

  • Bagaimana cara implementasinya di Golang?

Implementasi interface dan class di Golang

Karena di golang tidak ada class, maka kita memanfaatkan kecanggihan struct.

Caranya gampang:

  1. Definsikan ClockInterface:

    • method: SetTime()
    • method: GetTime()

    Sebagai catatan:
    Karena interface di golang hanya tersedia untuk method, maka field CurentTime dibuat di dalam struct.

  2. Implementasikan ClockInterface ke dalam clock struct

  3. Buat constructor

Kode utuhnya seperti berikut:

package main

import (
	"fmt"
	"time"
)

// Langkah ke-1: definisi interface
type ClockInterface interface {
	SetTime(t time.Time)
	GetTime() time.Time
}

// Langkah ke-2: implementasi interface
// --start--
type clock struct {
    // definisi field
	CurentTime time.Time
}

// implementasi method SetTime
func (c *clock) SetTime(time time.Time) {
	c.CurentTime = time
}

// implementasi method GetTime
func (c *clock) GetTime() time.Time {
	return c.CurentTime
}
// --end--

// Langkah ke-3: pembuatan constructor & inisialisasi CurentTime
func NewClock() ClockInterface {
	return &clock{CurentTime: time.Now()}
}

// Cara pemakaian
func main() {
	myclock := NewClock()
	fmt.Println(myclock)
}

What's next

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment