Browse Source

Add first exercices of chapter 07

master
T. Meissner 4 years ago
parent
commit
846a3f8a00
2 changed files with 96 additions and 0 deletions
  1. +34
    -0
      chapter_07/exercise_7.01/main.go
  2. +62
    -0
      chapter_07/exercise_7.02/main.go

+ 34
- 0
chapter_07/exercise_7.01/main.go View File

@ -0,0 +1,34 @@
package main
import "fmt"
type Speaker interface {
Speak() string
}
type person struct {
name string
age int
isMarried bool
}
func main() {
p := person{name: "Cailyn", age: 42, isMarried: false}
fmt.Println(p.Speak())
fmt.Println(p)
}
func (p person) String() string {
return fmt.Sprintf("%v (%v years old).\nMarried status: %v",
p.name, p.age, p.isMarried)
}
func (p person) Speak() string {
return "Hi, my name is " + p.name
}

+ 62
- 0
chapter_07/exercise_7.02/main.go View File

@ -0,0 +1,62 @@
package main
import "fmt"
type Shape interface {
Area() float64
Name() string
}
type triangle struct {
base float64
height float64
}
type rectangle struct {
length float64
width float64
}
type square struct {
side float64
}
func (t triangle) Area() float64 {
return (t.base * t.height) / 2
}
func (t triangle) Name() string {
return "triangle"
}
func (r rectangle) Area() float64 {
return r.length * r.width
}
func (r rectangle) Name() string {
return "rectangle"
}
func (s square) Area() float64 {
return s.side * s.side
}
func (s square) Name() string {
return "square"
}
func printShapeDetails(shapes ...Shape) {
for _, item := range shapes {
fmt.Printf("The area of %s is %.2f\n", item.Name(), item.Area())
}
}
func main() {
t := triangle{15.5, 20.1}
r := rectangle{20, 10}
s := square{10}
printShapeDetails(t, r, s)
}

Loading…
Cancel
Save