struct.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type Circle struct {
  7. x, y, r float64
  8. }
  9. type Rectangle struct {
  10. x1, y1, x2, y2 float64
  11. }
  12. func (c Circle) area() float64 {
  13. return math.Pi * c.r * c.r
  14. }
  15. func (r Rectangle) area() float64 {
  16. l := r.x2 - r.x1
  17. w := r.y2 - r.y1
  18. return l * w
  19. }
  20. type Person struct {
  21. Name string
  22. }
  23. func (p *Person) Talk() {
  24. fmt.Println("Hi, my name is", p.Name)
  25. }
  26. type Android struct {
  27. Person
  28. Model string
  29. }
  30. type Character struct {
  31. On bool
  32. Ammo int
  33. Power int
  34. }
  35. func (c *Character) Shoot() bool {
  36. if c.On == false {
  37. return false
  38. } else if c.Ammo > 0 {
  39. c.Ammo--
  40. return true
  41. } else {
  42. return false
  43. }
  44. }
  45. func (c *Character) RideBike() bool {
  46. if c.On == false {
  47. return false
  48. } else if c.Power > 0 {
  49. c.Power--
  50. return true
  51. } else {
  52. return false
  53. }
  54. }
  55. func main() {
  56. /*
  57. rect := Rectangle{x1: 0, y1: 0, x2: 10, y2: 10}
  58. circ := Circle{x: 0, y: 0, r: 5}
  59. fmt.Println("Rectangle area:", rect.area())
  60. fmt.Println("Circle area:", circ.area())
  61. */
  62. /*
  63. a := new(Android)
  64. a.Name = "Fedor"
  65. a.Person.Talk()
  66. a.Talk()
  67. */
  68. ch := Character{true, 5, 10}
  69. fmt.Println(ch.Shoot(), ch.Ammo, ch.Power)
  70. fmt.Println(ch.Shoot(), ch.Ammo, ch.Power)
  71. }