我正在使用 Rust 和 Diesel:
fn create_asset_from_object(assets: &HashMap<String, Assets_Json>) {
let connection: PgConnection = establish_connection();
println!("==========================================================");
insert_Asset(&connection, &assets);
}
pub fn insert_Asset(conn: &PgConnection, assests: &HashMap<String, Assets_Json>){
use self::schema::assets;
for (currency, assetInfo) in assests {
let new_asset = self::models::NewAssets {
asset_name: ¤cy,
aclass: &assetInfo.aclass,
altname: &assetInfo.altname,
decimals: assetInfo.decimals,
display_decimals: assetInfo.display_decimals,
};
//let result = diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post");
println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
}
}
编译器错误:
error[E0282]: type annotations needed
--> src/persistence_service.rs:107:81
|
107 | println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
| ^^^^^^^^^^ cannot infer type for `U`
最佳答案
我强烈建议你回去重读The Rust Programming Language ,特别是 chapter on generics .
fn get_result<U>(self, conn: &Conn) -> QueryResult<U>
where
Self: LoadQuery<Conn, U>,
换句话说,这意味着调用 get_result
的结果将是一个 QueryResult
,由 callers 选择的类型参数化;通用参数 U
。
您对 get_result
的调用绝不会指定 U
的具体类型。在许多情况下,类型推断用于了解类型应该是什么,但您只是打印值。这意味着它可以是任何实现特征并且可打印的类型,这还不足以做出最终决定。
您可以使用turbofish 运算符:
foo.get_result::<SomeType>(conn)
// ^^^^^^^^^^^^
或者您可以将结果保存到指定类型的变量中:
let bar: QueryResult<SomeType> = foo.get_result(conn);
如果您查看 Diesel tutorial ,您将看到这样的函数(我已对其进行编辑以删除不相关的细节):
pub fn create_post() -> Post {
diesel::insert(&new_post).into(posts::table)
.get_result(conn)
.expect("Error saving new post")
}
在这里,类型推断开始了,因为 expect
移除了 QueryResult
包装器并且函数的返回值必须是 Post
。逆向计算,编译器知道 U
必须等于 Post
。
如果您查看 documentation for insert
你可以看到,如果你不想取回插入的值,你可以调用 execute
:
diesel::insert(&new_user)
.into(users)
.execute(&connection)
.unwrap();
关于rust - 无法推断 `U` 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255634/