# panic：proto：以 nil 调用 Marshal

- **ID:** `go/proto-marshal-nil-message`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

以 nil 的 proto.Message 调用 google.golang.org/protobuf 的 Marshal/Unmarshal，通常是本应构建请求的函数返回了 nil 指针。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| google.golang.org/protobuf 1.28+ | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   Guard against nil before marshaling:
if req == nil {
    return status.Error(codes.InvalidArgument, "request is nil")
}
_ = req.ProtoReflect().IsValid()
   ```
2. **** (90% 成功率)
   ```
   Return value types instead of pointers from builders, or always allocate:
req := &pb.GetUserRequest{}
if userID != "" { req.Id = userID }
   ```

## 无效尝试

- **** — Recovering hides the nil bug; the request is still malformed and downstream calls fail silently. (80% 失败率)
- **** — proto.Clone(nil) also panics with the same message. (90% 失败率)
