实现说明
JSON ,string 标签与引号数字契约可以归结为函数 main。
2 处 err != nil 分支都调用 panic(err)——第一个失败就地终止程序,而不是带着坏状态继续跑。
使用要点
- 失败路径是
panic(err)——没有可检查的错误返回值,示例里也没有任何恢复机制。 - 每一步打印都带着自己的标签:
port=、bare number rejected:。
常见问题
错误处理是什么风格?
失败路径是 panic(err)——检测到的问题让运行终止,而不是被传回调用方。
运行「JSON ,string 标签与引号数字契约」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 port=、bare number rejected: 这类标签。
核心语句
if err != nil {
panic(err)
}
代码示例
package main
import (
"encoding/json"
"fmt"
)
// A legacy gateway contract sends numbers as JSON strings: the ,string option quotes them automatically
type Config struct {
Port int `json:"port,string"`
Timeout int64 `json:"timeout_ms,string"`
Retries uint8 `json:"retries,string"`
Host string `json:"host"`
}
func main() {
// Encoding: all three numeric fields emit as quoted strings
payload, err := json.Marshal(Config{Port: 8080, Timeout: 1500, Retries: 3, Host: "internal"})
if err != nil {
panic(err)
}
fmt.Println(string(payload))
// Decoding: quoted numbers are restored to their numeric types automatically
var cfg Config
quoted := []byte(`{"port":"9090","timeout_ms":"800","retries":"1","host":"backup"}`)
if err := json.Unmarshal(quoted, &cfg); err != nil {
panic(err)
}
fmt.Printf("port=%d timeout=%d retries=%d host=%s\n", cfg.Port, cfg.Timeout, cfg.Retries, cfg.Host)
// The contract is enforced: a bare number violates ,string and decoding fails outright
var bad Config
err = json.Unmarshal([]byte(`{"port":9090}`), &bad)
fmt.Println("bare number rejected:", err != nil)
}