Rustで文字列の扱いについて備忘録
Rustでは文字列の型にstr型とString型があります。str型はプリミティブ型で、String型は標準ライブラリです。
備忘録のためのメモです。
str型
str型は文字列スライスと呼ばれ、固定サイズで変更不可能。
//文字列を代入すると型推論でstr型に。 let a = "This is "; let b = "a pen."; //以下はコンパイルエラーにはならないが警告が出る。 let mut a = "This is "; //warning: variable does not need to be mutable
str型同士は連結できない。
let a = "This is a "; let b = "a pen."; //以下でコンパイルエラー let result = a + b; //error[E0369]: binary operation `+` cannot be applied to type `&str` //`+` cannot be used to concatenate two `&str` strings
その場合は最初の方のstr変数をString型に変換する(方法は以下の3つ)。一般的に使うのはto_string()
っぽい。
let result = a.to_owned() + b; let result = a.to_string() + b; let result = String::from(a) + b;
String型
String型は可変長文字列を扱えて変更も可能。
//新しい空のStringを生成 let a = String::new(); //文字列を代入しながら初期化 let a = String::from("This is a "); //文字列リテラルにto_string()でも可 let a = "This is a ".to_string();
String型同士は連結できない。
let a = String::from("This is a "); let b = "a pen.".to_string(); //以下でコンパイルエラー let result = a + b; //error[E0308]: mismatched types //expected &str, found struct `std::string::String` //help: consider borrowing here: `&b`
その場合は後ろの変数の頭に&
を入れて借用形にする。
let result = a + &b;
スポンサーリンク