postgresql - 如何将 Vec<i32> 转换为 types::array::ArrayBase<Option<i32>> 用于 rust-postgres?

标签 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]

最佳答案

技巧在于在 map |i| 的闭包函数中取消引用指针一些(*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();

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

关于postgresql - 如何将 Vec<i32> 转换为 types::array::ArrayBase<Option<i32>> 用于 rust-postgres?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184213/

相关文章:

c - 尝试从 C 连接到 postgres 时出现问题

database - psql : FATAL: password authentication failed for user error while trying to access psql

postgresql - 如何在 PostgreSQL 中创建 oid 类型的强制转换?

rust - 如何在可变引用结构中为字段交换新值?

rust - 如何在 Actix-Web 中为多种方法使用路由属性宏

java - 如何将不同模式的公共(public)数据插入到临时表中?

windows - postgresql 和防火墙

rust - 如何在 Rust 中获取当前平台的行尾字符序列?

rust - 默认发布版本是否始终使用 SSSE3 指令?

unit-testing - 当 `Result`不是 `Copy`时,设计单元测试