cast.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // --------------
  6. type Wallet struct {
  7. Cash int
  8. }
  9. func (w *Wallet) Pay(amount int) error {
  10. if w.Cash < amount {
  11. return fmt.Errorf("Not enough cash")
  12. }
  13. w.Cash -= amount
  14. return nil
  15. }
  16. // --------------
  17. type Card struct {
  18. Balance int
  19. ValidUntil string
  20. Cardholder string
  21. CVV string
  22. Number string
  23. }
  24. func (c *Card) Pay(amount int) error {
  25. if c.Balance < amount {
  26. return fmt.Errorf("Not enough money on balance")
  27. }
  28. c.Balance -= amount
  29. return nil
  30. }
  31. // --------------
  32. type ApplePay struct {
  33. Money int
  34. AppleID string
  35. }
  36. func (a *ApplePay) Pay(amount int) error {
  37. if a.Money < amount {
  38. return fmt.Errorf("Not enough money on account")
  39. }
  40. a.Money -= amount
  41. return nil
  42. }
  43. // --------------
  44. type Payer interface {
  45. Pay(int) error
  46. }
  47. // --------------
  48. func Buy(p Payer) {
  49. switch p.(type) {
  50. case *Wallet:
  51. fmt.Println("Оплата наличными?")
  52. case *Card:
  53. plasticCard, ok := p.(*Card)
  54. if !ok {
  55. fmt.Println("Не удалось преобразовать к типу *Card")
  56. }
  57. fmt.Println("Вставляйте карту,", plasticCard.Cardholder)
  58. default:
  59. fmt.Println("Что-то новое!")
  60. }
  61. err := p.Pay(10)
  62. if err != nil {
  63. fmt.Printf("Ошибка при оплате %T: %v\n\n", p, err)
  64. return
  65. }
  66. fmt.Printf("Спасибо за покупку через %T\n\n", p)
  67. }
  68. // --------------
  69. func main() {
  70. myWallet := &Wallet{Cash: 100}
  71. Buy(myWallet)
  72. var myMoney Payer
  73. myMoney = &Card{Balance: 100, Cardholder: "rvasily"}
  74. Buy(myMoney)
  75. myMoney = &ApplePay{Money: 9}
  76. Buy(myMoney)
  77. }