如何安全地缓存我的数据库导致内存缓存

I have function that returns a user. I am using gorm for my db ORM:

func (dbs *DbService) GetUser(userId string) User {
  var user = &User{}
  dbs.db..Find(&user)
  return user
}

If I cache the result i.e. the user, will this cause memory allocation issues because I am putting the user in the cache which is a reference type, so it will cause the variable user to live beyond the scope of this function?

Update

So given the function above, I want to update it to be cached using memcache (below is not the actual code to store my user, just an example):

mc.Set(&memcache.Item{Key: "foo", Value: []byte("my value")})

This is an out of process cache. I just want to know that if I store my user in this cache, it will not outlive my method call.

Memcache and Go variables (Go pointers) have nothing to do with each other.

Unless you use package unsafe, you (almost) never have to worry about Go variables and pointers: the garbage collector will free unreachable values, and it will never free reachable values. It's an invisible good so you don't have to think about that.

You can't store "Go variables" in memcache. You may store byte sequences (byte arrays) in memcache, but that will be independent of any Go variables. When you store a byte array in memcache, the byte sequence will be "copied".

If you want to store the value of a Go variable, you have to find a way to serialize the value, which may be using JSON or gob encoding, and the result byte sequence may be stored. While the encoded form sits in memcache, the Go variable may be freed (if there are no references to it).

When you need the cached value, you have to retrieve it from the memcache, and decode the byte slice (which is basically the reverse process of the serialization).