【问题标题】:Cannot infer type for `U`无法推断“U”的类型
【发布时间】:2018-02-25 14:15:41
【问题描述】:

我正在使用 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`

【问题讨论】:

  • 您的问题是什么?您刚刚粘贴了代码和一条错误消息。
  • 无法推断“U”的问题。
  • 问题很简单:如何解决编译问题?是的,罗伯特是正确的。
  • 通过为U 提供类型。
  • 我认为 OP 的混淆是正确的,因为客户端代码中没有 U,即使在错误消息中也没有 U。那么如何开始搜索需要指定的 U 呢?我认为这是一个有效的问题。

标签: rust rust-diesel


【解决方案1】:

我强烈建议您返回并重新阅读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();

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多