Creating a stopwatch in Go

Report a typo

Lena wants to create a simple stopwatch using Go. To do this, she has created the Stopwatch struct; it has two fields start and end of the time.Time type that will allow her to track time on her stopwatch.

Now Lena wants to create a few methods to make her stopwatch properly track time in her Go program:

  • Start() and End() — To make the s.start and s.end fields equal to time.Now()

  • TimeElapsed() — It should return the time elapsed by subtracting s.start from s.end by calling the s.end.Sub() method and passing to it the s.start time as an argument.

Tip: You can obtain the time elapsed via the s.end.Sub(s.start) statement.

Sample Input 1:

3

Sample Output 1:

Elapsed time: 3.0s
Write a program in Go
package main

import (
"fmt"
"time"
)

type Stopwatch struct {
start time.Time
end time.Time
}

// Create the Start(), End() and TimeElapsed() methods below:
func (s *?) Start() {
s.start = ?
}

func (s *?) ?() {
s.end = ?
}

func (s *?) ?() time.Duration {
return s.?.?(?)
}

// DO NOT delete or modify the contents of the main() function!
func main() {
var s Stopwatch
var seconds int
fmt.Scanln(&seconds)

s.Start()
time.Sleep(time.Duration(seconds) * time.Second)
s.End()
fmt.Printf("Elapsed time: %.3vs", s.TimeElapsed())
}
___

Create a free account to access the full topic