预期声明,找到了’IDENT’项

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

expected declaration, found 'IDENT' item

问题

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

import "appengine/memcache"

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

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

我是Go的新手,无法找出问题所在。

英文:

Im writing a small code using Memcache Go API to Get data stored in one of its keys . Here are few of lines of code i used ( got the code from Go app-engine docs )

import "appengine/memcache"

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

But the line 2 gives me a compilation error "expected declaration, found 'IDENT' item"

I'm new to Go , not able to figure out the problem

答案1

得分: 76

:= 短变量声明 只能在函数内部使用。

所以要么将 item 变量声明放在一个函数内,像这样:

import "appengine/memcache"

func MyFunc() {
    item := &memcache.Item {
        Key:   "lyric",
        Value: []byte("Oh, give me a home"),
    }
    // 对 item 进行操作
}

要么将其声明为全局变量并使用 var 关键字:

import "appengine/memcache"

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

The := Short variable declaration can only be used inside functions.

So either put the item variable declaration inside a function like this:

import "appengine/memcache"

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

Or make it a global variable and use the var keyword:

import "appengine/memcache"

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

答案2

得分: 0

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

我使用了以下的包名。

package go-example

看起来,这不是一个有效的包名。删除连字符后,它就可以工作了。

英文:

I was getting the same error, but the reason was completely different.

I was using following package name.

package go-example

Seems like, it's not a valid package name. After removing the hyphen, it worked.

答案3

得分: 0

这个错误也会在给一个变量赋值时出现,而该变量的名称是一个关键字,比如使用 var:= 2。这也会导致错误信息为"expected declaration, found 'IDENT' item"。所以请更正变量名称,问题就会解决。

英文:

This error also shows up when assigning value to a variable whose name is a keyword
Like using var:= 2
This also causes the error "expected declaration, found 'IDENT' item"
So correct the name and it will be fine

huangapple
  • 本文由 发表于 2015年3月9日 20:09:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/28941665.html
匿名

发表评论

匿名网友

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

确定