this repo has no description

:sparkles: (Go) pointers

Changed files
+99
Go
+38
Go/pointers/pointer.go
··· 1 + package pointers 2 + 3 + import ( 4 + "fmt" 5 + "errors" 6 + ) 7 + 8 + type Bitcoin int 9 + 10 + type Stringer interface { 11 + String() string 12 + } 13 + 14 + func (b Bitcoin) String() string { 15 + return fmt.Sprintf("%d BTC", b) 16 + } 17 + 18 + type Wallet struct { 19 + // when using lowercase properties names, it will be private 20 + balance Bitcoin 21 + } 22 + 23 + func (w *Wallet) Deposit(amount Bitcoin) { 24 + w.balance += amount 25 + } 26 + 27 + func (w *Wallet) Balance() Bitcoin { 28 + return w.balance 29 + } 30 + 31 + func (w *Wallet) Withdraw(amount Bitcoin) error { 32 + if amount > w.balance { 33 + return errors.New("cannot withdraw, insufficient funds") 34 + } 35 + 36 + w.balance -= amount 37 + return nil 38 + }
+61
Go/pointers/pointer_test.go
··· 1 + package pointers 2 + 3 + import "testing" 4 + 5 + func TestWallet(t *testing.T) { 6 + t.Run("deposit", func(t *testing.T) { 7 + wallet := Wallet{} 8 + 9 + wallet.Deposit(Bitcoin(10)) 10 + 11 + assertBalance(t, wallet, Bitcoin(10)) 12 + }) 13 + 14 + t.Run("withdraw", func(t *testing.T) { 15 + wallet := Wallet{balance: Bitcoin(20)} 16 + 17 + err := wallet.Withdraw(Bitcoin(10)) 18 + 19 + assertNoError(t, err) 20 + assertBalance(t, wallet, Bitcoin(10)) 21 + }) 22 + 23 + t.Run("withdraw insufficient funds", func(t *testing.T) { 24 + startingBalance := Bitcoin(20) 25 + wallet := Wallet{startingBalance} 26 + err := wallet.Withdraw(Bitcoin(100)) 27 + 28 + assertError(t, err, "cannot withdraw, insufficient funds") 29 + assertBalance(t, wallet, startingBalance) 30 + }) 31 + } 32 + 33 + func assertBalance(t testing.TB, wallet Wallet, want Bitcoin) { 34 + t.Helper() 35 + got := wallet.Balance() 36 + 37 + if got != want { 38 + t.Errorf("got %s want %s", got, want) 39 + } 40 + } 41 + 42 + func assertNoError(t testing.TB, got error) { 43 + t.Helper() 44 + 45 + if got != nil { 46 + t.Fatal("got an error butt didn't want one") 47 + } 48 + } 49 + 50 + 51 + func assertError(t testing.TB, got error, want string) { 52 + t.Helper() 53 + 54 + if got == nil { 55 + t.Fatal("didn't get an error but wanted one") 56 + } 57 + 58 + if got.Error() != want { 59 + t.Errorf("got %q, want %q", got, want) 60 + } 61 + }