Created
April 17, 2021 14:25
-
-
Save humamfauzi/011d162393e26085861a6af03ab9f6e5 to your computer and use it in GitHub Desktop.
Go Methods and Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
// We create a normat struct that represent normal inovice | |
type Invoice struct { | |
Id string | |
Amount int | |
isPaid bool | |
} | |
// Here is a method to alter the value of isPaid | |
// altering value require `*` sign before struct signature | |
// if there is no `*` then it wont be altered | |
func (i *Invoice) AlterToPaid() { | |
i.isPaid = true | |
} | |
// If the value does not alter, it is better to use | |
// non asterisk. | |
func (i Invoice) PrintStatus() { | |
fmt.Println(i.Id, "is paid? ", i.isPaid) | |
} | |
// Make another struct that requires an | |
// Invoice struct address | |
type Payment struct { | |
Invoice *Invoice | |
} | |
// Another example where it requires an | |
// actual Invoice | |
type PaymentLater struct { | |
Invoice Invoice | |
} | |
// Add method that return number | |
func (pl PaymentLater) GetSomeNumber() int { | |
return int(3) | |
} | |
// struct Payemnt engine inherit the Invoice component | |
// and all its method. there is an example later | |
type PaymentEngine struct { | |
PaymentLater | |
} | |
// Overriding the previous method | |
func (pe PaymentEngine) GetSomeNumber() int { | |
return pe.PaymentLater.GetSomeNumber() + 3 | |
} | |
func main() { | |
// both that invoice and invoice address should be able to | |
// access its own method | |
// example for actual invoice | |
i1 := Invoice{Id: "I1"} | |
i1.PrintStatus() | |
i1.AlterToPaid() | |
i1.Id = "I1 Alter" | |
i1.PrintStatus() | |
// example for address invoice | |
i2 := &Invoice{Id: "I2"} | |
i2.PrintStatus() | |
i2.AlterToPaid() | |
i2.Id = "I2 Alter" | |
i2.PrintStatus() | |
// both invoice should have its `isPaid` to be true | |
fmt.Println(i1, i2) | |
// Payment only accept invoice address not actual invoice | |
p1 := Payment{i2} | |
p1.Invoice.Id = "I2 Alter Payment" // will alter invoice id | |
fmt.Println(i1, i2) | |
// PaymentLater accept actual invoice | |
p2 := PaymentLater{i1} | |
p2.Invoice.Id = "I1 Alter Payment" // will not alter invoice id | |
fmt.Println(i1, i2) | |
// Method overriding | |
fmt.Println(p2.GetSomeNumber()) // should return 3 | |
pe := PaymentEngine{} // Not declaring PaymentLater as a input but still have its method | |
someNumber := pe.GetSomeNumber() // should return 3 + 3 = 6 | |
fmt.Println(someNumber) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment