expected declaration, found 'IDENT' item

Karthic Rao picture Karthic Rao · Mar 9, 2015 · Viewed 22.8k times · Source

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

Answer

icza picture icza · Mar 9, 2015

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"),
}