# panic：proto：Marshal 调用时传入 nil

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

## 根因

调用 proto.Marshal 时传入了 nil 的 *Message 指针。当未初始化的消息字段或 nil 响应直接传给 Marshal 时发生。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Guard against nil before marshalling:
if msg == nil {
    return nil, status.Error(codes.Internal, "nil message")
}
b, err := proto.Marshal(msg)
if err != nil { return nil, err }
   ```
2. **** (90% 成功率)
   ```
   Initialize nested message fields with proto message constructors instead of leaving them nil:
resp := &pb.Response{Data: &pb.Data{}} // not just &pb.Response{}
   ```

## 无效尝试

- **** — The nil message indicates a logic bug; swallowing the panic leaves a corrupt state and the message is never sent, causing silent data loss. (85% 失败率)
- **** — Marshalling an empty struct produces an empty byte slice, which downstream code interprets as a valid but empty message, corrupting semantics. (75% 失败率)
