参考“不是类型". -将类型存储在结构中 [英] Ref "is not a type" - storing a type in a struct

查看:51
本文介绍了参考“不是类型". -将类型存储在结构中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的文件:

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不是类型

Foo is not a type

我可能做错了很多.我想做的是将所有处理程序存储在AllHandlers结构中,但不确定如何执行该操作.

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
    }
}

上面的

不会编译,主要是因为据我所知,您将返回类型而不是值-例如,使用Class而不是该Class的实例.我该如何编译它?

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?

请参见以下示例: https://gist.github.com/ORESoftware/894438aee1d16aa9b2cb12ba25df274e

推荐答案

我解决了这个问题,诀窍是使用正确的语法.而不是这样做:

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
}

我这样做了:

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


type Foo = foo.Handler
type Bar = bar.Handler
type Baz = baz.Handler

然后我可以导入它,并使用Foo,Bar,Baz作为类型.因此,我认为您不能在结构中对类型进行分组,但是可以使用上述语法导入/导出类型.

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.

这篇关于参考“不是类型". -将类型存储在结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆