简体   繁体   English

如何转换Vec <i32> 到类型:: array :: ArrayBase <Option<i32> &gt;对于锈postgres?

[英]How to convert Vec<i32> to types::array::ArrayBase<Option<i32>> for rust-postgres?

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();

This results in the error: 这导致错误:

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

According to the documentation , this means that I need to convert it to types::array::ArrayBase<Option<i32>> . 根据文档 ,这意味着我需要将其转换为types::array::ArrayBase<Option<i32>>

How do I do this? 我该怎么做呢?


My best attempt so far is: 到目前为止,我最好的尝试是:

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();

Which results in: 结果是:

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

The trick lied in dereferencing the pointer within the closure function in map |i| Some(*i) 该技巧在于在映射|i| Some(*i)的闭包函数中取消对指针的引用|i| Some(*i) |i| Some(*i) : |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();

I'll award the answer to someone who can find a more elegant/ idiomatic way of doing this. 我会将答案授予能够找到更优雅/惯用的方法的人。

Try with either ArrayBase::from_raw or ArrayBase::from_vec . 尝试使用ArrayBase::from_rawArrayBase::from_vec They are documented - you can either read the source code or build the docs with rustdoc. 它们都有文档记录-您可以阅读源代码或使用rustdoc构建文档。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM