36

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

Karthic Rao
  • 3,624
  • 8
  • 30
  • 44

3 Answers3

76

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"),
}
icza
  • 389,944
  • 63
  • 907
  • 827
0

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.

Krishna
  • 6,107
  • 2
  • 40
  • 43
0

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

Freez
  • 53
  • 9