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

徘徊边缘 提交于 2020-01-30 06:41:45

问题


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

  |
7 |             if cell {
  |                ^^^^ expected bool, found &bool
  |
  = note: expected type `bool`
             found type `&bool`

if cell.clone() works for me but seems a bit hackisch.


回答1:


take a bool from a Vec<bool>

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 { /* ... */ }
}


来源:https://stackoverflow.com/questions/44788026/expected-type-bool-found-type-bool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!