0
0

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 3 years have passed since last update.

rustで関数内で呼び出し元にある変数の中身を書き換えるには

Posted at

main関数で存在する変数を別の関数内で書き換え

どうやってやるのかわかんなかった
教科書の最初の1ページにかかれてそうではあるが。

結論からいうと以下

fn add(a:&mut usize,b:usize){
    *a = *a + b
}

fn main() {
let mut a = 2;  
 add(&mut a,2);
println!("{:?}",a)
}

可変参照として渡してあげればよいようだ。
ちなみに引数のところのaは mut a として挙げても普通に動く。
一応ベクタの中身書き換えのやり方も。これで3,4,5のベクタが出てくる。

fn add(mut a:&mut Vec<usize>,b:usize){

    for i in a{
        *i = *i + b;
    }
}

fn main() {
let mut a = vec![1,2,3];  
 add(&mut a,2);
println!("{:?}",a)
}

ここまでやって書きたかったのは変数として渡さないグローバル的なやり方だったことを思い出した。
まあいいか

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?