New to Go and building a simple LRU cache in Go to get used to syntax and Go development.
Having an issue with the MoveToFront
list method, it fails on the following check in the MoveToFront
body
if e.list != l || l.root.next == e
I want to move the element (e) to the front of the list when I retrieve it from cache , like this
if elem, ok := lc.entries[k]; ok {
lc.list.MoveToFront(elem) // needs fixing
return elem
}
return nil
The Code can be seen here on line 32 the issue occurs
https://github.com/hajjboy95/golrucache/blob/master/lru_cache/lrucache.go#L32
There seem to be two problems, to me. First, this isn't how the List data type is meant to be used: lc.list.PushFront()
will create a List.Element
and return a pointer to it. That's not fatal, but at the least, it is kind of annoying—the caller has to dig through the returned List.Element
when using Get
, instead of just getting the value.
Meanwhile, presumably the failure you see is because you remove elements in Put
when the LRU-list runs out of space, but you don't remove them from the corresponding map. Hence a later Put
of the just-removed key will try to re-use the element in place, even though the element was removed from the list. To fix this, you'll need to hold both key and value. (In my simple experiment I did not see any failures here, but the problem became clear enough.)
I restructured the code somewhat and turned it into a working example on the Go Playground. I make no promises as to suitability, etc.