求Diesel SQL类型与Rust原生类型映射文档及编译错误解决方法
解决Diesel ORM中
f64无法实现diesel::Expression的问题 一、Diesel SQL与Rust类型核心映射
先明确你可能踩的类型匹配误区:
- 数据库
double precision→ Diesel schema类型Float8→ Rust类型f64(仅在启用对应feature时支持) - 数据库
numeric/decimal→ Diesel schema类型Numeric→ Rust类型BigDecimal(不能用f64,Diesel对f64的Expression支持不覆盖精确数值类型) - 数据库
money→ 需依赖diesel_moneycrate,对应RustMoney类型或BigDecimal
二、编译错误的具体解决步骤
修正结构体字段类型
如果用的是NUMERIC或money列,把结构体中的f64替换为BigDecimal,同时在Cargo.toml添加依赖:bigdecimal = "0.4" diesel = { version = "2.1", features = ["postgres", "numeric", "float8"] } # 根据你的数据库替换postgres为mysql/sqlite结构体示例:
use bigdecimal::BigDecimal; use diesel::Queryable; #[derive(Queryable)] #[diesel(table_name = cost_items)] struct CostItems { price: BigDecimal, }确保查询中类型匹配
若使用double precision+f64组合,查询时不要直接传递裸f64值,确保Diesel能识别其类型:let target_price = 19.99f64; let matching_items = cost_items::table .filter(cost_items::price.eq(target_price)) .load::<CostItems>(&db_conn)?;若仍报错,显式转换类型:
use diesel::dsl::cast; use diesel::sql_types::Float8; let items = cost_items::table .filter(cost_items::price.eq(cast(19.99f64, Float8))) .load::<CostItems>(&db_conn)?;检查Diesel feature启用情况
确保Cargo.toml中Diesel启用了对应类型的feature:- 支持
double precision:添加float8feature - 支持
numeric:添加numericfeature - 支持
money:添加moneyfeature(或使用diesel_moneycrate)
- 支持
三、类型映射的官方参考逻辑
Diesel的类型映射遵循精确匹配原则:
- 原生浮点类型仅对应数据库的浮点列(
double precision/real),且需启用对应feature - 精确数值(如金额、价格)必须用
BigDecimal对应numeric列,避免浮点精度丢失,同时Diesel的Expressiontrait对BigDecimal有完整支持 - 货币类型需借助第三方扩展,因为不同数据库的
money实现差异大
内容的提问来源于stack exchange,提问作者Chester C.
相关产品推荐
相关产品推荐

