22
11

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の関数の変数名の前のmut

Posted at

以下の関数romの引数を「fn qom(r:&mut str)」のように書くとエラーになる

#[allow(unused_assignments)]
fn main() {
    let mut p = "dummy strings";
    p = "Pom";
    println!("{}", p);
    qom(&mut p)
}

#[allow(unused_assignments)]
fn qom(r:&mut str){
    r = "Pom in qom";
    println!("{} in qom",r);
}

---エラー-----
error[E0308]: mismatched types
--> src/main.rs:15:9
|
15 | r = "Pom in qom";
| ^^^^^^^^^^^^ types differ in mutability
|
= note: expected type &mut str
found type &'static str
---エラー-----
しかし引数を「fn qom(mut r:&str)」のように書くとエラーにならない

#[allow(unused_assignments)]
fn main() {
    let mut p = "dummy strings";
    p = "Pom";
    println!("{}", p);
    qom(&mut p)
}

#[allow(unused_assignments)]
// 関数の引数のmutの位置ここでええんか?
fn qom(mut r:&str){
    r = "Pom in qom";
    println!("{} in qom",r);
}

関数の変数名の前のmutという書式がよくわからない
おんなじ疑問をもった人がいた。
https://users.rust-lang.org/t/solved-placement-of-mut-in-function-parameters/19891

「mut 変数名: 型」の場合、渡されたオブジェクトに対する可変な参照
(関数内の変数は変更できるが、渡されたオブジェクトは変更できない)

「変数名: &mut 型」の場合、渡された可変なオブジェクトに対する参照
(渡されたオブジェクト自身を変更できる)

「mut 変数名: 型」の例

fn main() {
    let pom = 4;
    println!("pom:{} [before test_fn]", pom);
    test_fn(pom);
    println!("pom:{} [after test_fn]", pom);
}

// 関数の引数の変数の前にmut
fn test_fn(mut pom:i32){
    println!("pom:{} [enter in test_fn]", pom);
    pom = 13;
    println!("pom:{} [changed in test_fn]",pom);
}

実行結果:
pom:4 [before test_fn]
pom:4 [enter in test_fn]
pom:13 [changed in test_fn]
pom:4 [after test_fn]

「変数名: &mut 型」の例

fn main() {
    let mut pom = 4;
    println!("pom:{} [before test_fn]", pom);
    test_fn(&mut pom);
    println!("pom:{} [after test_fn]", pom);
}

// 関数の引数の型の前に&mut
fn test_fn(pom:&mut i32){
    println!("pom:{} [enter in test_fn]", pom);
    *pom = 13;
    println!("pom:{} [changed in test_fn]",pom);
}

実行結果:
pom:4 [before test_fn]
pom:4 [enter in test_fn]
pom:13 [changed in test_fn]
pom:13 [after test_fn]

22
11
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
22
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?