dqj96395 2018-10-27 03:07
浏览 30
已采纳

引用“不是类型”-将类型存储在结构中

I have a file like so:

package foo
type Handler struct {}

and then in another file, I have:

import (
   "handlers/foo"
   "handlers/bar"
   "handlers/baz"
)

type AllHandlers struct {
    Foo foo.Handler
    Bar bar.Handler
    Baz baz.Handler
}

then in another file I have:

all := routes.AllHandlers{}
foo := all.Foo{}
bar := all.Bar{}
baz := all.Baz{}

but it gives me this error:

Foo is not a type

I am probably doing some egregiously wrong. What I want to do is store all handlers in the AllHandlers struct, but not sure how to do that.

I believe the question can be simplified in this way:

func (h HuruInjection) GetInjections() struct{} {
    return struct {
        Foo foo.Handler
        Bar  bar.Handler
        Baz baz.Handler
    }
}

the above won't compile, essentially because you are returning a type instead of a value, as far as I can tell - for example, a Class instead of an instance of that Class. How can I get this to compile?

See this example: https://gist.github.com/ORESoftware/894438aee1d16aa9b2cb12ba25df274e

  • 写回答

1条回答 默认 最新

  • doutang6130 2018-10-28 00:33
    关注

    I solved this problem, the trick is to use the right syntax. Instead of doing this:

    import (
       "handlers/foo"
       "handlers/bar"
       "handlers/baz"
    )
    
    type AllHandlers struct {
        Foo foo.Handler
        Bar bar.Handler
        Baz baz.Handler
    }
    

    I did this:

    import (
       "handlers/foo"
       "handlers/bar"
       "handlers/baz"
    )
    
    
    type Foo = foo.Handler
    type Bar = bar.Handler
    type Baz = baz.Handler
    

    then I could import this, and use Foo, Bar, Baz as types. So I don't think you can group types in a struct, but you can import/export types by using the above syntax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动