**在RPC函数中无法存储局部变量的值和地址**
```
protobuf文件
syntax = "proto3";
package message;
option go_package = "proto/;message";
service CreatorRoom{
rpc Creator (CreatorRoomReq) returns (CreatorRoomRes);
rpc JoinRoom (JoinRoomReq) returns (JoinRoomRes);
}```
所使用的结构体
```
type ClothesRoom struct {
RoomId string
Space string
Information map[string] *WholeRoom
Identification bool
TimeOut bool
CountDown int
WhoShot string
CardLib map[string][]int
}
func (rm *ClothesRoom) CreatorRoom(roomName string){
rm.RoomId = roomName
rm.Space = "55555555"
rm.Identification = false
rm.TimeOut= false
rm.CountDown= -1
rm.CardLib= make(map[string][]int)
}
```
**grpc处理请求函数**
```
func (poto * ProtoMessage) JoinRoom(cxt context.Context,in *pd.JoinRoomReq)(*pd.JoinRoomRes,error) {
coco:= new(ClothesRoom)
coco.CreatorRoom("lindejiang")
//UserList.GameServerMapList.RoomList是全局变量
UserList.GameServerMapList.RoomList[joinRoom.RoomId] = coco
}
```
下次再进来这个函数打印UserList.GameServerMapList.RoomList里面存的值得时候发现
里面存储的内存地址无效了,也就是出了JoinRoom这个函数之后就被gc了,我也尝试闭包也是会这样
上面UserList.GameServerMapList.RoomList[joinRoom.RoomId] = coco 出了函数之后就gc掉了
这就导致map里面存储的内存地址无效了导致报错
```
key:888999这个在别的函数存储一直都可以访问,key:545783是在grpc JoinRoom函数里存储的,出了函数就被gc掉了,内存地址是无效的,导致下面的错误
map[545783:0xc000208320 888999:0xc000096000]
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x8 pc=0x8ece5f]
```
有疑问加站长微信联系(非本文作者)