如何从 Rust 函数返回向量元素? [英] How do I return a vector element from a Rust function?

查看:75
本文介绍了如何从 Rust 函数返回向量元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个向量的元素:

I would like to return an element of a vector:

struct EntryOne {
    pub name: String,
    pub value: Option<String>,
}

struct TestVec {}

impl TestVec {
    pub fn new() -> TestVec {
        TestVec {}
    }

    pub fn findAll(&self) -> Vec<EntryOne> {
        let mut ret = Vec::new();
        ret.push(EntryOne {
            name: "foo".to_string(),
            value: Some("FooVal".to_string()),
        });
        ret.push(EntryOne {
            name: "foo2".to_string(),
            value: Some("FooVal2".to_string()),
        });
        ret.push(EntryOne {
            name: "foo3".to_string(),
            value: None,
        });
        ret.push(EntryOne {
            name: "foo4".to_string(),
            value: Some("FooVal4".to_string()),
        });

        ret
    }

    pub fn findOne(&self) -> Option<EntryOne> {
        let mut list = &self.findAll();

        if list.len() > 0 {
            println!("{} elements found", list.len());
            list.first()
        } else {
            None
        }
    }
}

fn main() {
    let test = TestVec::new();
    test.findAll();
    test.findOne();
}

(游乐场)

我总是收到这个错误:

error[E0308]: mismatched types
  --> src/main.rs:40:13
   |
35 |     pub fn findOne(&self) -> Option<EntryOne> {
   |                              ---------------- expected `std::option::Option<EntryOne>` because of return type
...
40 |             list.first()
   |             ^^^^^^^^^^^^ expected struct `EntryOne`, found &EntryOne
   |
   = note: expected type `std::option::Option<EntryOne>`
              found type `std::option::Option<&EntryOne>`

如何返回一个元素?

推荐答案

查看 Vec::first:

fn first(&self) -> Option<&T>

给定对向量的引用,如果有,它将返回对第一项的引用,否则返回None.这意味着包含值的向量必须比返回值的生命周期长,否则引用将指向未定义的内存.

Given a reference to a vector, it will return a reference to the first item if there is one, and None otherwise. That means that the vector containing the values must outlive the return value, otherwise the reference would point to undefined memory.

有两个主要途径:

  1. 如果您无法更改向量,则需要制作数据结构的副本.最简单的方法是使用 #[derive(Clone)] 注释结构.然后你可以调用 Option::clonedfirst 的结果上.

  1. If you cannot change the vector, then you will need to make a copy of your data structure. The easiest way to do this is to annotate the structure with #[derive(Clone)]. Then you can call Option::cloned on the result of first.

如果可以更改向量,则可以从中删除第一个值并返回它.有很多方法可以做到这一点,但最短的代码是使用 drain 迭代器.

If you can change the vector, then you can remove the first value from it and return it. There are many ways of doing this, but the shortest code-wise is to use the drain iterator.

#[derive(Debug, Clone)]
struct EntryOne {
    name: String,
    value: Option<String>,
}

fn find_all() -> Vec<EntryOne> {
    vec![
        EntryOne {
            name: "foo".to_string(),
            value: Some("FooVal".to_string()),
        },
        EntryOne {
            name: "foo2".to_string(),
            value: Some("FooVal2".to_string()),
        },
        EntryOne {
            name: "foo3".to_string(),
            value: None,
        },
        EntryOne {
            name: "foo4".to_string(),
            value: Some("FooVal4".to_string()),
        },
    ]
}

fn find_one_by_clone() -> Option<EntryOne> {
    find_all().first().cloned()
}

fn find_one_by_drain() -> Option<EntryOne> {
    let mut all = find_all();
    let mut i = all.drain(0..1);
    i.next()
}

fn main() {
    println!("{:?}", find_one_by_clone());
    println!("{:?}", find_one_by_drain());
}

其他更改:

  1. 如果没有状态,则不需要 TestVec;只需制作函数.
  2. Rust 风格是 snake_case 用于方法和变量名称.
  3. 在提供所有元素时使用 vec! 构造一个向量.
  4. 派生 Debug 以便您可以打印值.
  1. There's no need for TestVec if there's no state; just make functions.
  2. Rust style is snake_case for method and variable names.
  3. Use vec! to construct a vector when providing all the elements.
  4. Derive Debug so you can print the value.

<小时>

如果你想总是得到 last 元素,你可以使用 pop:


If you wanted to always get the last element, you can use pop:

fn find_one_by_pop() -> Option<EntryOne> {
    find_all().pop()
}

这篇关于如何从 Rust 函数返回向量元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆