在Golang中,如何将特定类型的地图定义为唯一类型?

在Golang中,如何将特定类型的地图定义为唯一类型?

问题描述:

So I'm at that awkward place where I'm trying to pass context data over to a template, and there's not a whole lot of really great examples out there that don't involve passing a preexisting structure. The best I have come up with is something like the following:

templ.Execute(writer, map[string]interface{}{
    "thingyA": ThingyA,
    "thingyB": ThingyB,
})

Using the above, I can reference ThingyA and all of its properties and methods in my template by using {{ .thingyA.[PROPERTY] }}. So that's pretty good in itself, in that it allows me to define a context in a simple Django-ish fashion, without using an anonymous struct, which would be a bit clunky.

But I'm wondering if there is some way to define a new type Context, so that I could simplify the above to the following:

templ.Execute(writer, Context{
    "thingyA": ThingyA,
    "thingyB": ThingyB,
})

That is, I would like to define a specific type Context that always has the form map[string]interface{}, and can be initialized in the same manner as a map. Any ideas on how to go about this?

所以我在那个尴尬的地方,试图将上下文数据传递到模板上, 那里并没有很多不涉及传递预先存在的结构的非常好的例子。 我想出的最好的东西是这样的: p>

  templ.Execute(writer,map [string] interface {} {
“ thingyA”:ThingyA,\  n“ thingyB”:ThingyB,
})
  code>  pre> 
 
 

使用上面的代码,我可以引用 ThingyA code>及其所有属性和方法 使用 {{.thingyA。[PROPERTY]}} code>在我的模板中。 因此,这本身就非常不错,因为它允许我以简单的Django风格定义上下文,而无需使用匿名结构,这会有些笨拙。 p>

我想知道是否有某种方法可以定义新的类型 Context code>,以便可以将以上内容简化为以下内容: p>

  templ.Execute  (作者,上下文{
“ thingyA”:ThingyA,
“ thingyB”:ThingyB,
})
  code>  pre> 
 
 

也就是说,我想定义 特定类型的 Context code>,其格式始终为 map [string] interface {} code>,并且可以与地图相同的方式进行初始化。 有关如何解决此问题的任何想法? p> div>

type Context map[string]interface{}
c := Context{"foo": 1, "bar": 2}

Playground.