Skip to content

Instantly share code, notes, and snippets.

@betandr
Created July 31, 2019 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betandr/a8adfa00a194325ed12ac9146c8ce82d to your computer and use it in GitHub Desktop.
Save betandr/a8adfa00a194325ed12ac9146c8ce82d to your computer and use it in GitHub Desktop.
Encapsulation with an interface
package account
import (
"errors"
)
type CheckingAccount struct {
balance int
}
func (a *CheckingAccount) Pay(amount int) error {
if a.balance-amount < 0 {
return errors.New("not enough funds")
}
a.balance = a.balance - amount
return nil
}
func (a *CheckingAccount) Deposit(amount int) {
a.balance = a.balance + amount
}
func (a *CheckingAccount) Balance() int {
return a.balance
}
func CreateAccount() *CheckingAccount {
return &CheckingAccount{}
}
// -----------------
package main
import (
"fmt"
"account"
)
type Account interface {
Pay(amount int) error
Deposit(amount int)
Balance() int
}
func main() {
var acc Account
acc = account.CreateAccount()
acc.Deposit(18)
fmt.Printf("balance is: %d\n", acc.Balance())
acc.Pay(10)
fmt.Printf("balance is: %d\n", acc.Balance())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment