< 返回版块

whfuyn 发表于 2020-08-06 21:11

Tags:pattern; reference; borrow

struct S {
    v: Option<String>,
}

fn main() {
    let v = "haha".to_owned();
    let s = &S{ v: Some(v) };
    // error[E0507]: cannot move out of `s.v` which is behind a shared reference
    if let (Some(ref v), true) = (s.v, true) { 

    }
    // ok
    if let Some(ref v) = s.v { 

    }
}

playground

当时没明白为什么前面加了ref还会提示从引用中移出值,后来一想真正发生移动的不是在前面那个Some(ref v)那,而是在(s.v, true)这里,因为这里要构建一个tuple

评论区

写评论
hellojukay 2020-08-07 13:02

这里想用自动类型推倒告诉 rustc 编译器不要 move 吗, 改成着就好了

struct S {
    v: Option<String>,
}

fn main() {
    let v = "haha".to_owned();
    let s = &S{ v: Some(v) };
    // error[E0507]: cannot move out of `s.v` which is behind a shared reference
    if let (Some(ref v), true) = (s.v, true) { 

    }
    // ok
    if let Some(ref v) = s.v { 

    }
}

和下面的这个问题一样的

fn func(str: &String){
}
fn main() {
    let s = String::from("hello worls");
    func(s);
    println!("{}",s);
}
phper-chen 2020-08-07 12:37

nice

1 共 2 条评论, 1 页