What is the difference between loop and while true?

前端 未结 4 1206
一向
一向 2021-02-05 02:11

The Rust tutorial, and now book claim there is a difference between while true and loop, but that it isn\'t super important to understand at this stage

4条回答
  •  余生分开走
    2021-02-05 02:55

    One major difference is that loop can return a value by passing a value to break. while and for will not:

    fn main() {
        let mut counter = 0;
    
        let result = loop {
            counter += 1;
    
            if counter == 10 {
                break counter * 2;
            }
        };
    
        assert_eq!(result, 20);
    }
    

提交回复
热议问题