Cannot call rusqlite's query because it expects the type &[&rusqlite::types::ToSql]

陌路散爱 提交于 2019-12-02 00:08:09

The compiler message isn't lying to you. You have a &[&String] not a &[&ToSql]. A trait object is a different type and often a different size from the underlying type; both are important considerations when packing values into a vector.

Another problem is that you cannot create a String, take a reference to it, then store that in a variable. The String would be deallocated immediately, leaving a dangling reference, so the compiler prevents that.

The easiest thing you can do is to create a new Vec that contains the trait object references:

let vec_values = vec![
    "test1".to_string(),
    "test2".to_string(),
    "test3".to_string(),
];

let query_values: Vec<_> = vec_values.iter().map(|x| x as &ToSql).collect();

let _rows = cached_statement.query(&query_values).unwrap();

(complete example)

Or if you wanted an overly-generic function to perform the conversion:

fn do_the_thing<'a, I, T: 'a>(things: I) -> Vec<&'a ToSql>
where
    I: IntoIterator<Item = &'a T>,
    T: ToSql,
{
    things
        .into_iter()
        .map(|x| x as &ToSql)
        .collect()
}
let _rows = cached_statement.query(&do_the_thing(&vec_values)).unwrap();

(complete example)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!