Vector 如何从Rust函数返回向量元素?

Vector 如何从Rust函数返回向量元素?,vector,reference,rust,Vector,Reference,Rust,我想返回向量的一个元素: struct EntryOne { pub name: String, pub value: Option<String>, } struct TestVec {} impl TestVec { pub fn new() -> TestVec { TestVec {} } pub fn findAll(&self) -> Vec<EntryOne> {

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

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();
}
struct EntryOne{
酒吧名称:String,
发布值:选项,
}
结构TestVec{}
impl TestVec{
pub fn new()->TestVec{
TestVec{}
}
发布fn findAll(和self)->Vec{
让mut ret=Vec::new();
后推(入口一){
名称:“foo”。to_string(),
值:Some(“FooVal.to_string()),
});
后推(入口一){
名称:“foo2”。to_string(),
值:Some(“FooVal2.to_string()),
});
后推(入口一){
名称:“foo3”。to_string(),
值:无,
});
后推(入口一){
名称:“foo4”。to_string(),
值:Some(“FooVal4.to_string()),
});
ret
}
发布fn findOne(&self)->选项{
让mut list=&self.findAll();
如果list.len()大于0{
println!(“{}找到元素”,list.len());
表1.first()
}否则{
没有一个
}
}
}
fn main(){
让test=TestVec::new();
test.findAll();
test.findOne();
}
()

我总是会遇到这样的错误:

错误[E0308]:类型不匹配
-->src/main.rs:40:13
|
35 | pub fn findOne(&self)->选项{
|------------由于返回类型,应为'std::option::option'
...
40 |列表第一()
|^^^^^^^^^^^^^应为结构“EntryOne”,已找到和EntryOne
|
=注意:应为'std::option::option'类型`
找到类型“std::option::option”`
如何返回元素?

查看签名:

其他更改:

  • 如果没有状态,就不需要
    TestVec
    ;只需生成函数即可
  • 方法和变量名的Rust样式为
    snake\u case
  • 在提供所有元素时,使用
    vec!
    构建一个向量
  • 派生
    Debug
    ,以便打印值

  • 如果希望始终获取最后一个元素,可以使用
    pop

    fn find_one_by_pop() -> Option<EntryOne> {
        find_all().pop()
    }
    
    fn通过\u pop()查找一个\u选项{
    查找所有内容().pop())
    }
    
    你理解值和对值的引用之间的区别吗?@MatthieuM.Ok,但是我如何按值返回元素?我可以克隆/复制它吗?@Shepmaster我已经尝试过了,但没有成功
    pub fn findOne(&self)->选项{self.findAll().first().cloned()}
    没有找到名为
    cloned
    的方法
    #[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());
    }
    
    fn find_one_by_pop() -> Option<EntryOne> {
        find_all().pop()
    }