如何将Vec <string>转换为&amp; [&gt; k :: ToValue]?

时间:2017-10-08 00:30:09

标签: vector rust gtk3 lifetime

我从嵌套循环和顺序重复嵌套循环中尝试了很多东西:

pub fn values_to_references<'a>(values_vector: Vec<String>) -> Vec<&'a gtk::ToValue> {
    values_vector
        .into_iter()
        .map(| item: String | &item.to_value() as &ToValue)
        .collect()
}

但无论我尝试什么,编译器总是告诉我item的生命周期太短:

borrowed value must be valid for the lifetime 'a as defined on the body at 87:89...
borrowed value does not live long enough (does not live long enough)

我需要转换为这些引用,以便将String添加到gtk::TreeModelgtk::TreeStore),这将远远超出其看似的范围。我可以找到的所有示例都使用对编译时已知的静态字符串的引用。这不是很有用。我的字符串来自JSON文件,在编译时无法识别。

我希望能够使用gtk::TreeModel

执行以下操作
model.insert_with_values(
    None,
    None,
    &[0, 1, 2, 3],
    to_value_items.as_slice());

我怎样才能做到这一点?

示例代码

我尝试将内容添加到gtk::TreeStoregtk::TreeModel的更多代码:

pub fn add_to_tree_store(tree_store: &TreeStore, row: Vec<String>) {
    tree_store.insert_with_values(
        None,
        None,
        &[0, 1, 2, 3],
        VocTreeView::strings_to_ampersand_str(row)
            .iter()
            .map(|x| x as &ToValue)
            .collect());
}

pub fn strings_to_ampersand_str<'res_ref>(values_vector: Vec<String>) -> Vec<&'res_ref str> {
    let append_values: Vec<_> = values_vector.iter().map(|x| &x[..]).collect();
    append_values
}

这在collect()

失败
a collection of type `&[&gtk::ToValue]` cannot be built from an iterator over elements of type `&gtk::ToValue` [E0277]

the trait bound `&[&gtk::ToValue]: std::iter::FromIterator<&gtk::ToValue>` is not satisfied (the trait `std::iter::FromIterator<&gtk::ToValue>` is not implemented for `&[&gtk::ToValue]`) [E0277]

似乎同样的问题又在咬我。

示例代码2

pub fn add_to_tree_store(tree_store: &TreeStore, row: Vec<String>) {
    tree_store.insert_with_values(
        None,
        None,
        &[0, 1, 2, 3],
        VocTreeView::values_to_references(&row)
            .iter()
            .map(|x| x as &gtk::ToValue)
            .collect());
}

pub fn values_to_references(values_vector: &[String]) -> Vec<&gtk::ToValue> {
    values_vector
        .into_iter()
        .map(|item| item as &gtk::ToValue)
        .collect()
}

这会在地图xcollect内遇到错误:

x

required for the cast to the object type `gtk::ToValue` [E0277]

required because of the requirements on the impl of `gtk::ToValue` for `&gtk::ToValue` [E0277]

required because of the requirements on the impl of `glib::value::SetValue` for `&gtk::ToValue` [E0277]

the trait bound `gtk::ToValue: glib::value::SetValue` is not satisfied (the trait `glib::value::SetValue` is not implemented for `gtk::ToValue`) [E0277]

collect

a collection of type `&[&gtk::ToValue]` cannot be built from an iterator over elements of type `&gtk::ToValue` [E0277]

the trait bound `&[&gtk::ToValue]: std::iter::FromIterator<&gtk::ToValue>` is not satisfied (the trait `std::iter::FromIterator<&gtk::ToValue>` is not implemented for `&[&gtk::ToValue]`) [E0277]

0 个答案:

没有答案
相关问题