Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
45: Working with Time and Durations
I've seen this mistake in almost every codebase I've inherited from developers moving to Go from languages like Python or JavaScript. They treat time as a raw number—usually an integer—and pass it around the application. It seems intuitive at first, but it's a recipe for a production outage that's incredibly frustrating to debug.
The ambiguity of raw integers
Imagine you're building a simple cache for a user session. You want to specify how long a session remains valid. A naive implementation might look like this:
func CreateSession(userID string, timeout int) {
// Assume we store this in Redis or a map
fmt.Printf("Session created for %s, expires in %d\n", userID, timeout)
}
// Calling the function
CreateSession("user_123", 30)
On the surface, this works. But here is where the friction starts: what does 30 actually mean? If you're the one who wrote the function, you know it's seconds. But six months from now, or for a new teammate, it's a guessing game. Is it milliseconds? Seconds? Minutes? I've spent hours debugging "ghost" bugs where one developer passed 30 meaning seconds, but the receiving function interpreted it as milliseconds, causing sessions to expire in 0.03 seconds.
When you use raw integers, you're relying on documentation or naming conventions (like timeoutSeconds) to enforce correctness. In a large project, that's a fragile strategy. You're essentially asking your teammates to keep a mental map of units for every single function call.
Letting the type system handle the units
In Go, we have time.Duration. It's not a complex object; it's actually just an int64 under the hood representing nanoseconds. However, because it's a distinct type, it allows us to be explicit. I always tell my juniors: if a function accepts a duration of time, it should never take an int.
Here is how we do this properly:
func CreateSession(userID string, timeout time.Duration) {
fmt.Printf("Session created for %s, expires in %v\n", userID, timeout)
}
// Now the call site is crystal clear
CreateSession("user_123", 30 * time.Second)
CreateSession("user_456", 5 * time.Minute)
By using time.Duration, the unit is baked into the call. You can't accidentally pass "30" and hope for the best because 30 is an untyped constant that won't automatically satisfy a time.Duration parameter in many contexts, and even when it does, 30 as a duration is 30 nanoseconds—which is so obviously wrong that it usually triggers a red flag during testing.
Where the logic actually breaks
The real danger happens when you start doing math with time. If you use integers, you're doing basic arithmetic. But if you use time.Time and time.Duration, you get access to methods that handle the edge cases for you. For example, if you want to check if a session has expired, you might be tempted to subtract two timestamps and compare the result to an integer.
Instead, use time.Since(). It's a convenience wrapper that reads like a sentence and prevents you from having to manually call time.Now().Sub(startTime) every single time. I find that the more I can move my time logic toward "readable prose" and away from "integer subtraction," the fewer bugs I ship.
One final tip: be careful when multiplying durations by variables. If you have a variable retryCount := 3 and you want to wait retryCount * time.Second, Go handles this fine because the constant time.Second promotes the expression to a duration. But if you're dealing with an integer variable from a config file, you'll need to cast it: time.Duration(configValue) * time.Second. It's a small bit of verbosity, but it's a fair price to pay for knowing exactly how many seconds your application is actually sleeping.
📋 Practical Task
Refactoring the Request Timeout Guard
You have been handed a piece of legacy code for a network proxy. The current implementation uses raw integers for timeouts, which has caused several "instant timeout" bugs because some developers are passing milliseconds while others pass seconds.
Your Task: Refactor the following code to use time.Duration instead of int. Ensure that the FetchData function is called with a duration of 5 seconds, and the WaitForRetry function is called with 2 seconds.
package main
import (
"fmt"
"time"
)
// TODO: Refactor this to use time.Duration
func FetchData(url string, timeout int) {
fmt.Printf("Fetching %s with a timeout of %d\n", url, timeout)
}
// TODO: Refactor this to use time.Duration
func WaitForRetry(attempts int, delay int) {
fmt.Printf("Retrying %d times with a delay of %d\n", attempts, delay)
}
func main() {
// These calls are currently ambiguous. Fix them.
FetchData("https://api.example.com", 5)
WaitForRetry(3, 2)
}
There are no comments for now.