`?` 运算符只能在返回 `Result` 或 `Option` (或实现 `std::ops::Try` 的其他类型)的函数中使用

2024-02-02

我正在做我的作业,其中包括与 Rust 中的数据库建立连接。我正在使用最新版本的 mysql crate:mysql ="18.2.0"。当我打印池变量时,我的数据库连接成功。我为表学生编写了自己的代码,但收到错误。然后我粘贴文档代码,我收到以下带有“?”的错误操作员:

我是第一次用 Rust 连接数据库。任何帮助表示赞赏。

warning: unused import: `std::io`
 --> src/main.rs:2:5
  |
2 | use std::io;
  |     ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:17:12
   |
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;
   | |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
...  |
58 | |
59 | | }
   | |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:19:16
   |
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;
18 | |
19 | | let mut conn = pool.get_conn()?;
   | |                ^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
...  |
58 | |
59 | | }
   | |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:22:1
   |
14 |  / fn insert(){
15 |  |
16 |  |
17 |  | let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;
...   |
22 | /| conn.query_drop(
23 | ||     r"CREATE TEMPORARY TABLE payment (
24 | ||         customer_id int not null,
25 | ||         amount int not null,
26 | ||         account_name text
27 | ||     )")?;
   | ||________^ cannot use the `?` operator in a function that returns `()`
...   |
58 |  |
59 |  | }
   |  |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:38:1
   |
14 |  / fn insert(){
15 |  |
16 |  |
17 |  | let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;
...   |
38 | /| conn.exec_batch(
39 | ||     r"INSERT INTO payment (customer_id, amount, account_name)
40 | ||       VALUES (:customer_id, :amount, :account_name)",
41 | ||     payments.iter().map(|p| params! {
...  ||
45 | ||     })
46 | || )?;
   | ||__^ cannot use the `?` operator in a function that returns `()`
...   |
58 |  |
59 |  | }
   |  |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:49:25
   |
14 |  / fn insert(){
15 |  |
16 |  |
17 |  | let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;
...   |
49 |  | let selected_payments = conn
   |  |_________________________^
50 | ||     .query_map(
51 | ||         "SELECT customer_id, amount, account_name from payment",
52 | ||         |(customer_id, amount, account_name)| {
53 | ||             Payment { customer_id, amount, account_name }
54 | ||         },
55 | ||     )?;
   | ||______^ cannot use the `?` operator in a function that returns `()`
...   |
58 |  |
59 |  | }
   |  |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

error: aborting due to 5 previous errors; 1 warning emitted

For more information about this error, try `rustc --explain E0277`.
error: could not compile `class-09`.

这是代码,我从文档复制来测试:

 use std::io;
    
    use mysql::prelude::*;
    use mysql::*;
    
    
    #[derive(Debug, PartialEq, Eq)]
    struct Payment {
        customer_id: i32,
        amount: i32,
        account_name: Option<String>,
    }

fn insert(){
    let pool = Pool::new("mysql://root:root@localhost:3306/Rust_testing")?;

let mut conn = pool.get_conn()?;

// Let's create a table for payments.
conn.query_drop(
    r"CREATE TEMPORARY TABLE payment (
        customer_id int not null,
        amount int not null,
        account_name text
    )")?;

let payments = vec![
    Payment { customer_id: 1, amount: 2, account_name: None },
    Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) },
    Payment { customer_id: 5, amount: 6, account_name: None },
    Payment { customer_id: 7, amount: 8, account_name: None },
    Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) },
];

// Now let's insert payments to the database
conn.exec_batch(
    r"INSERT INTO payment (customer_id, amount, account_name)
      VALUES (:customer_id, :amount, :account_name)",
    payments.iter().map(|p| params! {
        "customer_id" => p.customer_id,
        "amount" => p.amount,
        "account_name" => &p.account_name,
    })
)?;

// Let's select payments from database. Type inference should do the trick here.
let selected_payments = conn
    .query_map(
        "SELECT customer_id, amount, account_name from payment",
        |(customer_id, amount, account_name)| {
            Payment { customer_id, amount, account_name }
        },
    )?;

println!("Yay!");

}

fn main(){
    insert();
}

当我编写没有 ? 的代码时操作员,我收到以下错误:

warning: unused import: `std::io`
 --> src/main.rs:2:5
  |
2 | use std::io;
  |     ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0599]: no method named `query_drop` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
  --> src/main.rs:32:6
   |
32 | conn.query_drop(
   |      ^^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`

error[E0599]: no method named `exec_batch` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
  --> src/main.rs:48:6
   |
48 | conn.exec_batch(
   |      ^^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`

error[E0599]: no method named `query_map` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
  --> src/main.rs:60:6
   |
60 |     .query_map(
   |      ^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`

warning: unused import: `mysql::prelude`
 --> src/main.rs:4:5
  |
4 | use mysql::prelude::*;
  |     ^^^^^^^^^^^^^^

error: aborting due to 3 previous errors; 2 warnings emitted

For more information about this error, try `rustc --explain E0599`.
error: could not compile `class-09`.

正如编译器告诉您的那样:您的函数中缺少返回类型。 这 ?运算符将返回(传播)错误(如果有),但要使其正常工作,您需要有一个可以使用错误类型构造的返回类型。

对于原型设计,您只需调用 unwrap 即可。但在编写生产代码时应仔细考虑这种方法,因为当函数返回错误时,它只会使程序崩溃。

寻找更多

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

`?` 运算符只能在返回 `Result` 或 `Option` (或实现 `std::ops::Try` 的其他类型)的函数中使用 的相关文章

  • PHP多图像文件上传并存储到文件夹和数据库

    我正在建立一个网站 向夜间狂欢者展示大城市夜总会场所和活动的列表 我正在尝试构建一个后端页面 管理员可以在其中添加俱乐部并输入信息 例如机构名称 位置 相对价格等 当然还有俱乐部的一些图像 每个俱乐部必须至少有一张图像 即主图像 可以有额外
  • 这是什么意思? “这正是因为不应该为库的所有用户确定性地重新编译库。”

    我是 Rust 新手 正在尝试了解 Cargo 的事情 我在他们的常见问题解答中读到 为什么二进制文件在版本控制中有 Cargo lock 但库没有 https doc rust lang org cargo faq html why do
  • PHP:如何检查总数。 URL 中的参数?

    我正在使用 REQUEST 检索参数 有没有办法找到总数 URL 中的参数 而不是检索每个参数然后进行计数 这将为您提供总数 分隔的 URL 查询参数 count explode SERVER QUERY STRING 如果您只想要唯一的参
  • Innodb页面大小设置

    在innodb中 页面大小默认为16kb 如何将页面大小设置为 8kb 是否有在源编译步骤中设置的选项 您不需要在源编译步骤中指定页面大小 MySQL 5 6 及更高版本支持不同的页面大小 无需重新编译 但是 您必须在初始化 InnoDB
  • 在 Mac OSX 上交叉编译 x86_64-unknown-linux-gnu 失败

    我尝试将我的 Rust 项目之一编译到 x86 64 unknown linux gnu 目标 cargo build target x86 64 unknown linux gnu Compiling deployer v0 1 0 fi
  • 使用 php 和 mysql 计算日期差(以小时为单位)

    我如何使用 php 和 mysql 找到以小时为单位的日期差异 Use TIMEDIFF http dev mysql com doc refman 5 1 en date and time functions html function
  • 使用 MySQL 的 CURDATE() 或 PHP 的 date() 更快?

    使用mysql查询是不是更快 SELECT CURDATE as today 或 PHP 语句 curdate date Y m d 同样的答案是否适用于使用date VS MySQL 的NOW and CURTIME 如果您只是执行查询以
  • 使用 Sequelize (NodeJS) 代替 * 指定特定字段

    好吧 我在 NodeJS 中有一个项目 我正在其中使用 Sequelize 来实现 MySQL ORM 这件事工作得非常好 但是我试图弄清楚是否有一种方法可以指定在查询的基础上返回哪些字段 或者是否有一种方法可以在某处执行 query 例如
  • 我不断收到此 mysql 错误代码 #1089

    CREATE TABLE movies movie movie id INT 3 NULL AUTO INCREMENT movie name VARCHAR 25 NULL movie embedded id VARCHAR 50 NUL
  • PDO获取最后插入的ID

    我有一个查询 我想获取插入的最后一个 ID 字段ID是主键并且自动递增 我知道我必须使用这个声明 LAST INSERT ID 该语句适用于如下查询 query INSERT INTO cell place ID VALUES LAST I
  • MySQL InnoDB引擎是否对只读事务运行任何性能优化

    根据参考文档 只读事务标志可能会提示存储引擎运行一些优化 设置会话事务只读 如果事务访问模式设置为 READ ONLY 则对表进行更改 被禁止 这可能使存储引擎能够提高性能 不允许写入时可能进行的改进 InnoDB引擎是否对只读事务运行这样
  • 使用 Laravel 和 Eloquent 从表中选择全部

    我正在使用 Laravel 4 设置我的第一个模型 以从名为的表中提取所有行posts 在标准 MySQL 中我会使用 SELECT FROM posts 如何在 Laravel 4 模型中实现这一目标 我的完整模型源代码如下
  • Mysql 将 --secure-file-priv 选项设置为 NULL

    我在 Ubuntu 中运行 MySQL 我在运行特定的查询集时收到此错误 MySQL 服务器正在使用 secure file priv 选项运行 因此无法执行此语句 当我这样做的时候SELECT secure file priv 在我的 m
  • MySQL 组合两个查询

    我有两个 MySQL 查询 QUERY SELECT sodnik 1 FROM prihodnji krog WHERE file id 8778 AND sodnik 1 UNION SELECT sodnik 2 FROM priho
  • 使用表白名单选项更新 Debezium MySQL 连接器

    我正在使用 Debezium 0 7 5 MySQL 连接器 并且我试图了解如果我想使用以下选项更新此配置 最好的方法是什么table whitelist 假设我创建了一个连接器 如下所示 curl i X POST H Accept ap
  • mysql时间比较

    我有 job start 和 job end 时间 timediff 会给我时间差 现在我想看看这项工作是否花费了超过 2 小时 30 分钟 我如何比较它 如果我这样做 我会收到错误 timediff job start job end g
  • 迁移问题:MS SQL > MySQL:插入缓冲区内存

    我在使用 MySQL Workbench 上的内置迁移工具时遇到问题 我正在将一个非常大的数据库从 MS SQL 2014 迁移到 MySQL MS SQL 服务器本地部署在我的 Windows 8 1 桌面上 MySQL 服务器在我的网络
  • Rust 中的表达式模板实现类似于 boost::yap

    我正在尝试自学 Rust 作为一个具有挑战性的学习项目 我想复制 C 表达式模板库的设计模式提升 雅普 https www boost org doc libs 1 74 0 doc html yap html 我不需要一个完整的实现 我只
  • Rust 枚举中 str/String 值的最佳实践是什么?

    我有一个非常赏心悦目的东西 但我担心它的含义 derive Eq PartialEq Debug pub enum SmtpHost DOMAIN String IPV4 Ipv4Addr IPV6 Ipv6Addr UNKNOWN lab
  • 无法加载身份验证插件“caching_sha2_password”

    我正在将 MySQL 8 0 与 MySQL Workbench 连接并收到以下错误 无法加载身份验证插件 caching sha2 password dlopen usr local mysql lib plugin caching sh

随机推荐