预期声明,找到 'IDENT' 项

expected declaration, found 'IDENT' item

我正在使用 Memcache Go 编写一小段代码 API 以获取存储在其中一个键中的数据。这是我使用的几行代码(从 Go app-engine docs 获得代码)

import "appengine/memcache"

item := &memcache.Item {
Key:   "lyric",
Value: []byte("Oh, give me a home"),
}

但是第2行给我一个编译错误"expected declaration, found 'IDENT' item"

我是 Go 的新手,无法弄清楚问题

:=Short variable declaration只能在函数内部使用。

所以要么将 item 变量声明放在这样的函数中:

import "appengine/memcache"

func MyFunc() {
    item := &memcache.Item {
        Key:   "lyric",
        Value: []byte("Oh, give me a home"),
    }
    // do something with item
}

或者使它成为全局变量并使用var关键字:

import "appengine/memcache"

var item = &memcache.Item {
    Key:   "lyric",
    Value: []byte("Oh, give me a home"),
}

我遇到了同样的错误,但原因完全不同。

我使用的是以下包名。

package go-example

好像不是有效的包名。删除连字符后,它起作用了。

为名称为关键字的变量赋值时也会出现此错误 就像使用 var:= 2 这也会导致错误“expected declaration, found 'IDENT' item” 所以把名字改正就好了