如何将Vec <i32>转换为types :: array :: ArrayBase <option <i32>&gt;生锈的帖子?</option <i32> </i32>

时间:2014-08-07 13:44:39

标签: postgresql rust

let ids: Vec<i32> = get_ids(); //get_ids impl elsewhere
let stmt = db_conn.prepare(
    "SELECT id, name, created FROM person
    WHERE id = ANY( $1 )").unwrap();
let mut iter = stmt.query(
    [&ids]).unwrap();

这会导致错误:

error: failed to find an implementation of trait postgres::types::ToSql for collections::vec::Vec<i32>

根据the documentation, 这意味着我需要将其转换为types::array::ArrayBase<Option<i32>>

我该怎么做?


到目前为止,我最好的尝试是:

let idOptions: Vec<Option<i32>> = ids.iter().map( |i| Some(i) ).collect();
let idsForDb: postgres::types::array::ArrayBase<Option<i32>> =
    postgres::types::array::ArrayBase::from_vec(idOptions, 0);
let mut iter = stmt.query(
    [&idsForDb]).unwrap();

结果是:

error: expected core::iter::FromIterator<core::option::Option<&i32>>, but found core::iter::FromIterator<core::option::Option<i32>> (expected i32 but found &-ptr) [E0095]

2 个答案:

答案 0 :(得分:1)

这个技巧在地图|i| Some(*i)中的闭包函数中取消引用指针时说谎:

let idOptions: Vec<Option<i32>> = ids.iter().map( |i| Some(*i) ).collect();
let idsForDb: postgres::types::array::ArrayBase<Option<i32>> =
    postgres::types::array::ArrayBase::from_vec(idOptions, 0);
let mut iter = stmt.query(
    [&idsForDb]).unwrap();

我会给那些能找到更优雅/惯用方法的人奖励答案。

答案 1 :(得分:0)

尝试使用ArrayBase::from_rawArrayBase::from_vec。它们被记录在案 - 您可以阅读源代码或使用rustdoc构建文档。

https://github.com/sfackler/rust-postgres/blob/master/src/types/array.rs