我可以直接匹配一个生锈的字符串,正如我们在这个例子中看到的那样.
let a = "hello".to_string();
match &a[..] {
    "hello" => {
        println!("Matches hello");
    }
    _ => panic!(),
}
但是,如果我有一个选项类型,它会失败.
match Some(a) {
    Some("hello") => {
        println!("Matches some hello");
    }
    _ => panic!(),
}
因为类型不匹配.
error[E0308]: mismatched types
 --> src/main.rs:5:14
  |
5 |         Some("hello") => {
  |              ^^^^^^^ expected struct `std::string::String`, found reference
  |
  = note: expected type `std::string::String`
             found type `&'static str`
我无法做到这一点,String因为我们有一个[..].到目前为止,我提出的最好的是:
match Some(a) {
    Some(b) => match (&b[..]) {
        "hello" => {
            println!("Matches some, …我正在尝试实现一个常用的模式 - 在下一个循环迭代中使用上一个循环迭代的结果。例如,要实现分页,您需要给出上一页上最后一个值的 id。
struct Result {
    str: String,
}    
fn main() {
    let times = 10;
    let mut last: Option<&str> = None;
    for i in 0..times {
        let current = do_something(last);
        last = match current {
            Some(r) => Some(&r.str.to_owned()),
            None => None,
        };
    }
}
fn do_something(o: Option<&str>) -> Option<Result> {
    Some(Result {
        str: "whatever string".to_string(),
    })
}
但是,我不确定如何真正从循环中获取值。目前,编译器错误是temporary value dropped while borrowed(at &r.str.to_owned()),虽然我做了很多其他尝试,但都无济于事。
我发现真正让它工作的唯一方法是创建某种局部tmp_str变量并像这样进行黑客攻击:
match current {
    Some(r) => {
        tmp_str.clone_from(&r.str);
        last = …我希望这两个代码示例的结果相同:
let maybe_string = Some(String::from("foo"));
let string = if let Some(ref value) = maybe_string { value } else { "none" };
let maybe_string = Some(String::from("foo"));
let string = maybe_string.as_ref().unwrap_or("none");
第二个示例给了我一个错误:
let maybe_string = Some(String::from("foo"));
let string = if let Some(ref value) = maybe_string { value } else { "none" };
我有一个Option<String>和一个功能,需要一个Option<&str>.我认为Option::as_ref会工作,因为通常会&String自动转换为&str,但不是在这里.我收到此错误:
sandbox.rs:6:27: 6:37 error: mismatched types:
 expected `core::option::Option<&str>`,
    found `core::option::Option<&collections::string::String>`
(expected str,
    found struct `collections::string::String`) [E0308]
虽然这个答案描述了如何从一个转换到另一个,但我仍然想知道为什么不像&String通常那样"强迫"(如果这是正确的术语)&str.
我尝试将解包的字符串引用发送到为结构实现的静态方法。这是一个简化的代码:
fn main() {
    let a = A {p: Some("p".to_string())};
    a.a();
}
struct A {
    p: Option<String>
}
impl A {
    fn a(self) -> Self {
        Self::b(&self.p.unwrap());
        self
    }
    fn b(b: &str) {
        print!("b: {}", b)
    }
}
它失败:
fn main() {
    let a = A {p: Some("p".to_string())};
    a.a();
}
struct A {
    p: Option<String>
}
impl A {
    fn a(self) -> Self {
        Self::b(&self.p.unwrap());
        self
    }
    fn b(b: &str) {
        print!("b: {}", b)
    }
}
我认为实施Copy特征不是解决方案。在那种情况下, …
我正在尝试继续Option<Vec<>>.
#[derive(Debug)]
pub struct Person {
    pub name: Option<String>,
    pub age: Option<u64>,
}
#[derive(Debug)]
pub struct Foo {
    pub people: Option<Vec<Person>>,
}
天真的我正在使用
for i in foo.people.iter() {
    println!("{:?}", i);
}
Vec我没有遍历所有元素,而是实际显示整体Vec.这就像我在迭代唯一的参考Option.
使用以下内容,我正在迭代Vec内容:
for i in foo.people.iter() {
    for j in i.iter() {
        println!("{:?}", j);
    }
}
我不确定这是最令人愉快的语法,我相信你应该解开第Option一个实际迭代的集合.
Option::iter如果你总是有一个参考,那么我看不到你实际可以使用的地方.
这是游乐场的链接.
当我有一个Option并想要一个内部的东西或创建一些东西,如果它是一个None我得到一个错误.
示例代码:
fn main() {
    let my_opt: Option<String> = None;
    let ref_to_thing = match my_opt {
        Some(ref t) => t,
        None => &"new thing created".to_owned(),
    };
    println!("{:?}", ref_to_thing);
}
错误:
error[E0597]: borrowed value does not live long enough
  --> src/main.rs:6:18
   |
6  |         None => &"new thing created".to_owned(),
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
   |                  |                            |
   |                  |                            temporary value dropped here while still borrowed
   |                  temporary value does not live long enough
...
10 | }
   | …我有一个Option包含一些 JSON 的。如果是Some,则必须转换内部 JSON,但如果是None,则必须保留None。
这就是我目前实施的方式:
struct One;
struct Other;
impl One {
    pub fn convert(&self) -> Other {
        Other {}
    }
}
fn example(attr: Option<One>) -> Option<Other> {
    match attr {
        Some(attr) => Some(attr.convert()),
        None => None,
    }
}
我是新来的锈和不完全获得时使用的复杂性match,if let或时使用的?运营商。
我的实现是 Rust 惯用的吗?对我来说似乎比较冗长,而且看起来像一个到处都会出现的模式,所以我可以想象这可以更简洁地处理;是这样吗?
我如何match在枚举引用上?我使用的依赖项返回对枚举的引用,我需要读取枚举包含的值。在下面的例子中,我关心的事情是分配final_val有x:
fn main() {
    let test_string = String::from("test");
    let option: std::option::Option<String> = Some(test_string);
    let ref_option = &option;
    let final_val = match ref_option {
        Some(x) => x,
        _ => String::from("not Set"),
    };
    println!("{:?}", final_val);
}
如果我遵循编译器的建议并&在类型中添加 aSome和ref x:
fn main() {
    let test_string = String::from("test");
    let option: std::option::Option<String> = Some(test_string);
    let ref_option = &option;
    let final_val = match ref_option {
        &Some(ref x) => x,
        _ => String::from("not Set"),
    }; …我正在尝试使用该retain(...)方法从向量中过滤掉值.目前,我的代码到目前为止
let results = get_data(); // Returns Result<Vec<MyData>, Box<Error>>
match results {
    Ok(mut my_data) => {
        // Make sure that `name` is not None
        myData.retain(|ref d| d.name.is_some());
        // Only keep data if 'name' is in this list
        let names = ["Alice", "Bob", "Claire"];
        my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
    },
    Err(_) => {}
}
但是,这会产生错误
|
|     my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
|                                           ^^^^^^^^^^^^^^^^^^^^^^^^ expected &str, found str
|
= note: expected type `&&str`
           found type `&str`
看起来编译器在这里告诉我两个不同的东西,但在这两种情况下它似乎都想要一个额外的参考.但是,当我尝试将相关行更改&names.contains(d.name.unwrap().as_str())为时,编译器会抛出以下错误.
|
|     my_data.retain(|ref …