无法构建简单的 Golang 代码 – 切片字面量语法

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

Cannot build simple golang code - Slice literal syntax

问题

我正在尝试使用go-dockerclient构建一个简单的Golang程序。

  1. package main
  2. import (
  3. docker "github.com/fsouza/go-dockerclient"
  4. )
  5. func main() {
  6. h := &docker.HostConfig{
  7. Memory: 4194304,
  8. MemorySwap: -1,
  9. CPUShares: 5,
  10. NetworkMode: "host",
  11. }
  12. client, err := docker.NewClient("unix:///var/run/docker.sock")
  13. config := &docker.Config{
  14. Env: []string{"FOO=foo"},
  15. Image: "redis",
  16. }
  17. opts := docker.CreateContainerOptions{
  18. Config: config,
  19. HostConfig: h,
  20. }
  21. container, _ := client.CreateContainer(opts)
  22. err = client.StartContainer(container.ID)
  23. }

这给我返回了以下错误信息:

  1. :~/gosrc/src/github.com/achanda$ go build
  2. # github.com/achanda
  3. ./main.go:16: syntax error: unexpected comma
  4. ./main.go:22: non-declaration statement outside function body
  5. ./main.go:23: non-declaration statement outside function body
  6. ./main.go:24: non-declaration statement outside function body
  7. ./main.go:25: syntax error: unexpected }

我似乎没有找到语法上的错误(尽管我是个新手)。问题是什么?

英文:

I am trying to build a simple golang program using go-dockerclient

  1. package main
  2. import (
  3. docker "github.com/fsouza/go-dockerclient"
  4. )
  5. func main () {
  6. h := &docker.HostConfig {
  7. Memory: 4194304,
  8. MemorySwap: -1,
  9. CPUShares: 5,
  10. NetworkMode: "host",
  11. }
  12. client, err := docker.NewClient("unix:///var/run/docker.sock")
  13. config := &docker.Config {
  14. Env: ["FOO=foo"],
  15. Image: "redis",
  16. }
  17. opts := docker.CreateContainerOptions {
  18. Config: config,
  19. HostConfig: hostConfig,
  20. }
  21. container, _ := client.CreateContainer(opts)
  22. err = client.StartContainer(container.ID)
  23. }

This gives me:

  1. :~/gosrc/src/github.com/achanda$ go build
  2. # github.com/achanda
  3. ./main.go:16: syntax error: unexpected comma
  4. ./main.go:22: non-declaration statement outside function body
  5. ./main.go:23: non-declaration statement outside function body
  6. ./main.go:24: non-declaration statement outside function body
  7. ./main.go:25: syntax error: unexpected }

I don't seem to find anything wrong with the syntax (admittedly a noob though). What is the problem?

答案1

得分: 2

切片字面值应该像这样:

  1. []string{"a", "b", "c"}

而不是像这样:

  1. ["a", "b", "c"]

所以将这个代码片段:

  1. Env: ["FOO=foo"],

改为:

  1. Env: []string{"FOO=foo"},
英文:

Slice literals should look like this:

  1. []string{"a", "b", "c"}

Not like this:

  1. ["a", "b", "c"]

So change this:

  1. Env: ["FOO=foo"],

To this:

  1. Env: []string{"FOO=foo"},

huangapple
  • 本文由 发表于 2015年10月2日 13:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/32900985.html
匿名

发表评论

匿名网友

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

确定