float64 can only be truncated to an integer type when truncation is enabled

使用 mongo-go-dirver 反序列化到 float32 报错

error decoding key weight: float64 can only be truncated to an integer type when truncation is enabled

问题描述

通过 mongo-go-dirver findOne 查数据并反序列化到 结构体时,有个字段:

type User struct {
    Name      string    `bson:"name"`
    Age       uint32    `bson:"age"`
    Weight    float32   `bson:"weight"`
    Studying  bool      `bson:"studying"`
    Tag       []string  `bson:"tag"`
    CreatedAt time.Time `bson:"created_at"`
}

weight 字段类型为 float32,就提示:

float64 类型的值只能在启用截断时截断为整数类型

问题如何产生的

存入数据时,手写 68.1,在 Golang 中手写的 float 值默认为 float64, 所以就当 float64 存入mongo了,待你想反序列化到 float32的值时,就报错了。

在 mgo 中,程序会自动帮你截断转换了,但是在 mongo-go-driver 中需要手动处理,或者显示得配置解决方案,不然会导致报错,不输出数据!

解决否

已解决

方案

问题原因时 浮点数 decode时,超出了精度,mongo-go-driver就把这个问题抛了个error出来。那么针对这个报错,我们可以从两方面去解决。要么提高精度,要么高速golang,多的截断,咋不要了。

  1. 把float32改为 float64
  2. 在bson tag 追加 ,truncate
    Weight    float32   `bson:"weight,truncate"`

参考

  • https://segmentfault.com/a/1190000038451313

发表评论

邮箱地址不会被公开。 必填项已用*标注