参数数量/类型不匹配

时间:2015-06-11 13:33:10

标签: rust lifetime

extern crate postgres;

use postgres::{Connection, SslMode};

struct User {
    reference: String,
    email: String,
    firstname: String,
    lastname: String
}

static DB_URI: &'static str = "postgres://postgres:postgres@localhost/test";

fn main() {

    let conn = Connection::connect(DB_URI, &SslMode::None).unwrap();
    let trans = conn.transaction().unwrap();

    //...

}

fn insert_user<'a>(trans: &'a postgres::Transaction, user: &User) -> &'a postgres::Result {
    //...
}

正在抛出错误

error: wrong number of type arguments: expected 1, found 0 [E0243]
fn insert_user<'a>(trans: &'a postgres::Transaction, user: &User) -> &'a postgres::Result {
                                                                         ^~~~~~~~~~~~~~~~

这里缺少什么?我只想返回执行查询的结果。

UPDATE 所以我修改了这样的功能行:

fn insert_user(trans: &postgres::Transaction, user: &User) -> &postgres::Result<()> {

欺骗编译器显示正确的返回类型,它给了我这个:

mismatched types:
 expected `core::result::Result<(), postgres::error::Error>`,
    found `core::result::Result<postgres::Rows<'_>, postgres::error::Error>`

然而,当我尝试匹配这样的返回类型时:

fn insert_user(trans: &postgres::Transaction, user: &User) -> &postgres::Result<postgres::Rows<'_>, postgres::error::Error> {

它现在抛出一个新错误:

error: use of undeclared lifetime name `'_` [E0261]
fn insert_user(trans: &postgres::Transaction, user: &User) -> postgres::Result<postgres::Rows<'_>, postgres::error::Error> {
                                                                                              ^~

2 个答案:

答案 0 :(得分:4)

查看包postgres的{​​{3}},我们可以看到postgres::Result类型在一个类型参数上是通用的:

type Result<T> = Result<T, Error>;

通常你会有两个选择:

  1. 如果你知道它是什么,请自己指定类型:postgres::Result<MyType>
  2. 让编译器为您推断(如果其他地方有足够的信息):postgres::Result<_>
  3. 但是在返回类型(->之后的内容)类型推断未触发时,因此只有选项1可用。

    (提示:你仍然有一个技巧可以找到所需的类型。你可以尝试指定单位类型:... -> postgres::Result<()>并检查编译器是否抱怨错误,例如“expected {{1 },找到MyType“。这意味着您要指定()。)

答案 1 :(得分:2)

Result定义为postgres::Result<T>(我们说它是泛于T )。根据insert_user函数的内部结构,它可以是Result<bool>Result<u64>Result<()>或其他内容。

例如,execute上的Transaction方法会返回Result<u64>,因此这可能是变体。