Skip to content

Instantly share code, notes, and snippets.

@ejholmes
Created May 26, 2018 01:50
Show Gist options
  • Save ejholmes/bc2575c03729542bdd0fa28370daefc6 to your computer and use it in GitHub Desktop.
Save ejholmes/bc2575c03729542bdd0fa28370daefc6 to your computer and use it in GitHub Desktop.
Satisfying interfaces in Go using struct members and packages
package main
import "time"
type Time interface {
Now() time.Time
}
type fakeTime struct {
Now func() time.Time
}
func main() {
// Why don't struct members staisfy interfaces?
t := &fakeTime{
Now: func() time.Time {
return time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
},
}
new(fakeTime).(Time)
// ./main.go:20:15: invalid type assertion: new(fakeTime).(Time) (non-interface type *fakeTime on left)
// Why don't packages satisfy interfaces?
time.(Time)
// ./main.go:24:6: use of package time without selector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment