Rust warning「warning: variable does not need to be mutable」が発生した場合の対処法

Rust warning「warning: variable does not need to be mutable」が発生した場合の対処法

Rustで、warning「warning: variable does not need to be mutable」が発生した場合の対処法を記述してます。「mutable」に設定している値をコード内で変更していない場合に発生します。Rustのバージョンは1.62.0を使用してます。

環境

  • OS windows11 home
  • rustc 1.62.0

warning全文

以下のコードで発生

fn main() {

    let mut str: String = "hello".to_string();

    println!("{}", str);

}

warning全文

warning: variable does not need to be mutable
 --> sample.rs:3:9
  |
3 |     let mut str: String = "hello".to_string();
  |         ----^^^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` on by default

warning: 1 warning emitted

原因

変更可能な「mutable」に設定しているが、コードでは変更していないため

対処法

変更する必要がなければ「mut」を削除する

fn main() {

    let mut str: String = "hello".to_string();

    println!("{}", str);

}