doumei1772 2014-11-11 15:55
浏览 17
已采纳

A型满足B型要求

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
}
  • 写回答

1条回答 默认 最新

  • duanpuqi9965 2014-11-11 16:01
    关注

    The DatabaseHandler satisfies the ChannelHandler interface with this method:

    func (d *databaseHandler) ProcessChannels(f *Feed, ch []*Channel)
    

    The interface requires:

    type ChannelHandler interface {
        ProcessChannels(f *Feed, newchannels []*Channel)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mysql sum函数优化
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题
  • ¥20 基于matlab的航迹融合 航迹关联 航迹插补
  • ¥15 用Matlab实现图中的光线追迹