du0204 2018-10-27 17:55
浏览 57
已采纳

声明一个类型,其中该类型是一个返回struct {}的函数

I have this:

type HandlerCreator = func() struct{}

I am trying to declare a type, where the type is a func that returns a struct{} value.

so, yeah, a HandlerCreator might look like:

type Handler struct{}

func CreateHandler() Handler {
    return Handler{}
}

and I am trying to use that type in a map:

var Handlers = map[string]HandlerCreator{
    "Register": register.CreateHandler,  // <<<< compile error
}

but it says:

cannot use register.CreateHandler (type func() register.Handler) as type func() struct {} in map value

anyone know how to do this?

Golang won't even let me do this:

var Handlers = map[string]func(){
    "Register": register.CreateHandler,
}

I get this error:

cannot use register.CreateHandler (type func() register.Handler) as type func() in map value

again, CreateHandler is just a simple func, shown above.

  • 写回答

1条回答 默认 最新

  • duanlian1320 2018-10-27 18:03
    关注

    When you say

    type Handler struct{}
    

    then the Handler type and an empty structure are different types. Therefore, a function returning Handler and a function returning struct{} are also of different types.

    If I was doing it, I'd change the "creator" type to return the renamed return type

    type HandlerCreator = func() Handler
    

    but it should also work to change the function to return struct{}, or to change Handler to a type alias.

    type Handler = struct{} // the "=" is important
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部