rust - 无法推断 `U` 的类型

标签 rust rust-diesel

我正在使用 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: &currency,
            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 .


LoadDsl::get_result定义为:

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/

相关文章:

postgresql - 如何使用柴油进行 IN 查询?

postgresql - 如何在安装时修复 Rust 柴油 cli 链接 libpq.lib 错误

rust - 可以在没有#[derive(Serialize)] 的情况下在枚举上实现/派生 Serialize 吗?

iterator - 如何在 String 中使用 contains() 和 retain()?

rust - 如何从迭代器中获取切片?

vector - 将Map <Vec <u8>,Vec <u8 >>展平为Vec <u8>,然后将其返回到Map <Vec <u8>,Vec <u8 >>

rust - 如何通过 wasm-pack 将 Rust Wasm 应用程序与 libpq 链接起来?

rust - 为什么我会收到一个简单的 trait 实现的 "overflow evaluating the requirement"错误?

rust - 编译器强制我实现特征方法,但我的类型永远不会满足方法上的 `Self` 特征绑定(bind)

rust - Diesel 可以在运行时更改模式吗?