在Golang中,我如何定义一个特定类型的映射作为唯一类型?

huangapple go评论91阅读模式
英文:

In Golang, how do I define a specific sort of map as a unique type?

问题

所以我现在处于一个尴尬的境地,我正在尝试将上下文数据传递给模板,但是没有太多真正好的例子,这些例子不涉及传递预先存在的结构。我能想到的最好的方法是像下面这样:

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

使用上述方法,我可以通过{{ .thingyA.[PROPERTY] }}在模板中引用ThingyA及其所有属性和方法。这本身就很好,因为它允许我以简单的Django风格定义上下文,而不使用匿名结构,这会有点笨拙。

但是我想知道是否有一种方法可以定义一个新类型Context,这样我就可以简化上述代码,如下所示:

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

也就是说,我想定义一个特定类型的Context,它始终具有map[string]interface{}的形式,并且可以像初始化映射一样进行初始化。有关如何实现这一点的任何想法吗?

英文:

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?

答案1

得分: 4

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

Playground.

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

Playground.

huangapple
  • 本文由 发表于 2014年8月6日 00:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/25143461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定