I have a question about a data type/structure being able to satisfy the requirements of another type that's expected in a function call.
In feed.go of an RSS and Atom feed handler written in Go, there is a New
helper function that takes a ChannelHandlerFunc as a third argument, which you can see gets passed as a parameter to a NewDatabaseChannelHandler
, which returns a DatabaseHandler, as you can see below. A DatabaseHandler has a ChannelHandler embedded in it. You can see in the New
function that the return value of NewDatabaseChannelHandler (i.e. the DatabaseHandler) gets passed as the 3rd parameter to NewWithHandlers
. However, NewWithHandlers
as you can see, requires a ChannelHandler as the third parameter.
Question: Why doesn't NewWithHandlers
throw an error when it's passed the DatabaseHandler
as a return value from NewDatabaseChannelHandler
as a third parameter. NewWithHandlers
expects a ChannelHandler not a DatabaseHandler?
func New(cachetimeout int, enforcecachelimit bool, ch ChannelHandlerFunc, ih ItemHandlerFunc) *Feed {
db := NewDatabase()
f := NewWithHandlers(cachetimeout, enforcecachelimit, NewDatabaseChannelHandler(db, ch), NewDatabaseItemHandler(db, ih))
f.database = db
return f
}
then NewWithHandlers accepts a ChannelHandler as a third argument
// NewWithHandler creates a new feed with handlers
// People should use this approach from now on
func NewWithHandlers(cachetimeout int, enforcecachelimit bool, ch ChannelHandler, ih ItemHandler) *Feed {
v := new(Feed)
v.CacheTimeout = cachetimeout
v.EnforceCacheLimit = enforcecachelimit
v.Type = "none"
v.channelHandler = ch
v.itemHandler = ih
return v
}
This file is the source code for the NewDatabaseChannelHandler
However, NewDatabaseChannelHandler doesn't return a ChannelHandler, it returns a DatabaseHandler
func NewDatabaseChannelHandler(db *database, chanhandler ChannelHandler) ChannelHandler {
database := new(databaseHandler)
database.db = db
database.chanhandler = chanhandler
return database
}
type databaseHandler struct {
db *database
itemhandler ItemHandler
chanhandler ChannelHandler
}