# panic：proto：使用 nil 调用 Marshal

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

## 根因

使用 nil 消息指针调用 proto.Marshal，通常是因为某函数返回了 (nil, nil) 或结构体字段未初始化。

## 版本兼容性

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

## 解决方案

1. **** (92% 成功率)
   ```
   Guard against nil before marshaling:
if msg == nil { return errors.New("nil message") }
b, err := proto.Marshal(msg)
   ```
2. **** (90% 成功率)
   ```
   Fix the producer function to never return (nil, nil):
func build() (*pb.Msg, error) {
  if bad { return nil, errBad }
  return &pb.Msg{...}, nil
}
   ```

## 无效尝试

- **** — Hides the bug; the caller still receives garbage or a swallowed error. (80% 失败率)
- **** — Masks the real problem (nil constructor) and may send semantically empty data. (70% 失败率)
