liveBook · Manning

Time.Now

As explained in 100 Go Mistakes and How to Avoid Them

time.Now is a Go standard-library function that returns the current local time as a time.Time value.

time.Now returns the current local time as a time.Time. Calling it inside time-sensitive logic can make tests brittle because execution delays change the observed boundary. section 11.6

A timing-dependent test

A cache test creates events with time.Now().Add offsets, trims entries older than 15 milliseconds, and expects two events. If the machine becomes busy, the moving clock can produce a different result. section 11.6

type Cache struct {
    mu     sync.RWMutex
    events []Event
}
 
type Event struct {
    Timestamp time.Time
    Data string
}
 
func (c *Cache) TrimOlderThan(since time.Duration) {
    c.mu.RLock()
    defer c.mu.RUnlock()
 
    t := time.Now().Add(-since)               #1
    for i := 0; i < len(c.events); i++ {
        if c.events[i].Timestamp.After(t) {
            c.events = c.events[i:]           #2
            return
        }
    }
}

Inspect the direct implementation: TrimOlderThan computes a cutoff with time.Now().Add(-since) before scanning time-sorted events. section 11.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates direct implementation, failure-prone tests, and several clock-control approaches without covering every time-API technique.
Examples
Uses a time-sorted event cache, millisecond offsets, fixed timestamps, and a stubbed clock.
What it assumes
Assumes familiarity with Go methods, time.Duration, time.Time, unit tests, and basic dependency injection.
What you can do after
Diagnose brittle time-based tests and apply dependency injection or explicit timestamps to make clock-dependent behavior deterministic.
How it connects
Connects time.Now with time.Time, unit testing, dependency injection, stubs, and time-based cache trimming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.