Expected type `bool`, found type `&bool`

后端 未结 1 601
执笔经年
执笔经年 2021-01-23 01:33

I would like to take a bool from a Vec and compare it in an if statement. How do I solve the following error?



        
1条回答
  •  心在旅途
    2021-01-23 02:09

    take a bool from a Vec

    Just do that:

    let foo = vec![true];
    if foo[0] { /* ... */ }
    

    bool implements Copy, so indexing the array will copy the value out.

    If you had a reference to the boolean inside the vector, you will need to dereference it:

    let foo = vec![true];
    if let Some(val) = foo.last() {
        if *val { /* ... */ }
    }
    

    Or

    let foo = vec![true];
    if let Some(&val) = foo.last() {
        if val { /* ... */ }
    }
    

    0 讨论(0)
提交回复
热议问题