Last active
August 29, 2015 14:14
-
-
Save toastdriven/89b32306159f90cbebfa to your computer and use it in GitHub Desktop.
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 ( | |
"container/list" | |
"fmt" | |
"time" | |
) | |
func main() { | |
l := list.New() | |
now := time.Now() | |
l.PushFront(now) | |
// Here's where the problem begins. When you fetch the first item, | |
// you get an `Element`, not the value you pushed. It's a struct with | |
// a single external field, `Value interface{}`. | |
front := l.Front() | |
// This code doesn't work & blows up. | |
// """front.Value.Year undefined (type interface {} has no field or method Year)""" | |
// fmt.Print(front.Value.Year()) | |
// I tried a type assertion, to fix what the compiler grumped about. | |
// But somehow messed this up, because at the time I was storing a pointer to `now` in the list, rather than... the value? | |
// t := front.Value.(time.Time) | |
// In retrospect, this is the same as the solution below & IDFK. | |
// Tried to cast it as a pointer failed. | |
// var grump *time.Time | |
// t, ok : = front.Value.(time.Time) | |
// grump = (*time.Time)(t) | |
// Still kaboom: """cannot convert t (type time.Time) to type *time.Time""" | |
// fmt.Print(t.Year()) | |
// Eventually, after an hour or so of source-diving & searching, I | |
// tried this, which (spoiler alert) works: | |
if t, ok := front.Value.(time.Time); ok { | |
fmt.Print(t.Year()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment