Why does Volumes of CreateContainerOptions take a map[string]struct{}?

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

Why does Volumes of CreateContainerOptions take a map[string]struct{}?

问题

我一直在使用由fsouza创建的优秀的go-dockerclient,但我对于为什么docker.CreateContainerOptions.Volumes是一个字符串到结构体的映射感到困惑。

文档没有解释为什么会这样,但我想你只需要使用map[string] => string来将主机卷映射到容器卷,或者将值留空以表示主机卷将被挂载到容器内的相同路径。

我查看了一堆Github上的开源代码,看到很多人在创建容器时只是使用一个字符串和一个空结构体作为卷的值进行挂载。

我对Go也是新手,所以可能漏掉了一些非常明显的东西。

英文:

I've been using the great go-dockerclient] created by fsouza but I'm confused why docker.CreateContainerOptions.Volumes is a map of strings to structs?

The docs don't explain why this is but I'd imagine that you'd just need map[string] => string to map host volumes to container volumes? Or leave the value blank to say that the host volume will be mounted at the same path within the container.

I looked through a bunch of open code on Github with people creating containers but I just saw a lot of examples of people mounting Volumes with just a string and an empty struct as the value.

I'm also new to Go so I might be missing something entirely obvious.

答案1

得分: 6

空结构体是Go语言中唯一占用0字节内存的类型。

当你想要存储某种信息或者表示某种信号时,使用空结构体是一种常见的习惯用法。但是这种信息应该尽可能小。

在你的情况下,

map[string]struct{}

被用来仅存储映射的键,而没有关联的值。
这样你可以快速检查映射是否包含某个键(它基本上是一个集合)。

这里有一些使用空结构体的示例。

英文:

The empty struct is the only type in go that occupies 0 (zero) Bytes of memory.

It is a common idiom to use an empty struct when you want to store something or signal something. But that something should be as small as possible.

In your case

map[string]struct{}

Is used to store just the map's keys with no values associated.
This way you can quickly check if the map contains a key or not. (It's basically a set).

Here are a few examples of what you can do with empty structs.

答案2

得分: 2

我不确定这个包的具体工作方式,但是map[string]struct{}是Golang中表示集合的惯用方式。所以我猜测地图的键必须包含卷的完整路径...

英文:

I don't know exactly how this package works, but map[string]struct{} is the Golang idiomatic way of representing a set. So my guess is that the key of the map must contain the full path of the volume...

huangapple
  • 本文由 发表于 2016年2月12日 02:49:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/35347596.html
匿名

发表评论

匿名网友

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

确定