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?
Karena di golang tidak ada class
, maka kita memanfaatkan kecanggihan struct
.
Caranya gampang:
-
Definsikan
ClockInterface
:- method:
SetTime()
- method:
GetTime()
Sebagai catatan:
Karenainterface
di golang hanya tersedia untukmethod
, maka fieldCurentTime
dibuat di dalamstruct
. - method:
-
Implementasikan
ClockInterface
ke dalam clockstruct
-
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)
}