Type Assertions
A variable of interface type holds a concrete value inside it. Sometimes you need to get that concrete value back out, for example to read a field that isn't part of the interface. You do that with a type assertion:
var b Bentuk = Persegi{Sisi: 4}
p := b.(Persegi) // ambil nilai Persegi dari b
fmt.Println(p.Sisi) // 4
Here b.(Persegi) pulls the Persegi value out of b. If your guess about the type is wrong, this form will panic and the program stops. That's why you should almost always use the comma ok form:
l, ok := b.(Lingkaran)
if !ok {
fmt.Println("b bukan Lingkaran")
}
(That prints "b isn't a Lingkaran" — a circle.)
- If
breally does hold aLingkaran,okistrueandlholds the value. - If not,
okisfalseandlholds the zero value ofLingkaran— no panic.
A type assertion can also ask whether a value satisfies another interface:
if s, ok := b.(fmt.Stringer); ok {
fmt.Println(s.String())
}
Task
A chat app sends notifications through several channels. They all satisfy the Notifikasi interface:
type Notifikasi interface {
Isi() string
}
The Email, SMS, and Push types are already provided, along with their Isi() methods. Complete these two functions using a comma ok type assertion:
func alamatEmail(n Notifikasi) (string, bool)— ifnis anEmail, return itsAlamat(address) field andtrue; otherwise return""andfalse.func biayaKirim(n Notifikasi) int— ifnis anSMS, the sending cost is350(rupiah per SMS); other channels are free (0).