3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustのforループを参照で回す

Last updated at Posted at 2020-02-01

そこまで難しい事でもないのですが、見当たらなかった上小一時間悩んだので
書き留めておきます。

ソース

fn main(){
    let mut hoge = [0,1,2,3,4,5];

    // 参照かつmutableな状態でループ
    for i in &mut hoge{
        *i = *i + 1; //値の書き換え
    }

    // 参照でのループ(mutableなし)
    for i in &hoge{
        println!("{}",i);
    }
}

結果は以下の通り

1
2
3
4
5
6

もちろん、vecなんかも同じノリで普通に回せます

//上のソースをvecにしただけ
fn main(){
    let mut hoge = vec![0,1,2,3,4,5];

    for i in &mut hoge{
        *i = *i + 1; //値の書き換え
    }

    for i in &hoge{
        println!("{}",i);
    }
}
1
2
3
4
5
6
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?