diff --git a/chapter_07/exercise_7.01/main.go b/chapter_07/exercise_7.01/main.go new file mode 100644 index 0000000..6373a48 --- /dev/null +++ b/chapter_07/exercise_7.01/main.go @@ -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 + +} diff --git a/chapter_07/exercise_7.02/main.go b/chapter_07/exercise_7.02/main.go new file mode 100644 index 0000000..7acba40 --- /dev/null +++ b/chapter_07/exercise_7.02/main.go @@ -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) + +}