3 ms·
It's unfortunate that Go's time library cannot represent an infinite duration, or timestamps in the infinite past or infinite future. This makes it difficult t
by p1mrx 11y ago
It's unfortunate that Go's time library cannot represent an infinite duration, or timestamps in the infinite past or infinite future. This makes it difficult to represent things like "this cache entry never expires", without relying on auxiliary data.
Also, the minimum/maximum timestamp and overflow behavior seem to be poorly-defined.
- nulltype 11y agoYou could use the zero value (t.IsZero()) for that if you wanted to. That might be more confusing than a boolean flag though.
- p1mrx 11y agoIsZero works okay as an "infinite past" value, such as marking that a cache entry has already expired, but it's cumbersome to use as an "infinite future" because zero is naturally less than all the timestamps you're likely to encounter. It's also not a great idea to manually define the largest possible timestamp as a sentinel, because Add(Duration) doesn't check for overflow.
- colin_mccabe 11y agoYou can use nil to represent "no expiration."
- p1mrx 11y agoTime is a struct, so nil is not a legal value. You would have to store a pointer (var t *time.Time) instead.
- colin_mccabe 11y agoYes, I was suggesting storing a pointer to the entire structure.
- eru 11y agoIf only Go had better support for algebraic data structures..
- rakoo 11y agoI believe the idiomatic way would be to have 2 "Add" functions: func (c *Cache) AddExpiring(k Key, e Entry, d time.Duration) {} func (c *Cache) Add(k Key, e Entry) {} func (c *Cache) GetWithRemaining(k Key) (e Entry, left time.Duration) {} Not the prettiest, but it does the job. That sentence could be Go's motto.