Created
July 24, 2019 16:19
-
-
Save betandr/c2ca88df325cb846de197df9c94dfd41 to your computer and use it in GitHub Desktop.
Ambiguous struct embedding resolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strconv" | |
) | |
type Cycle struct{} | |
func (g *Cycle) time(distance float64) float64 { | |
// using speed = distance / time | |
return 60 * distance / 15 | |
} | |
type Walk struct{} | |
func (g *Walk) time(distance float64) float64 { | |
// using speed = distance / time | |
return 60 * distance / 5 | |
} | |
// CycleAndWalk half walking, half cycling | |
type CycleAndWalk struct { | |
Cycle | |
Walk | |
} | |
func (g *CycleAndWalk) time(distance float64) float64 { | |
cycling := g.Cycle.time(distance) / 2 | |
walking := g.Walk.time(distance) / 2 | |
return walking + cycling | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("usage: travel n.n (where n.n is the distance in km such as 3.4)") | |
os.Exit(0) | |
} | |
distance, err := strconv.ParseFloat(os.Args[1], 64) | |
if err != nil { | |
fmt.Printf("can't calculate distance of %s", os.Args[1]) | |
os.Exit(0) | |
} | |
c := &Cycle{} | |
fmt.Printf("Cycling %.2fkm would take %.2f minutes\n", distance, c.time(distance)) | |
w := &Walk{} | |
fmt.Printf("Walking %.2fkm would take %.2f minutes\n", distance, w.time(distance)) | |
cw := &CycleAndWalk{} | |
fmt.Printf("Cycling %.2fkm then walking %.2fkm would take %.2f minutes\n", distance/2, distance/2, cw.time(distance)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment