Rustが文字の配列を実装する方法は2つあります。strとStringです。
strは「文字列スライス」とも呼ばれ、通常は&strのように参照と組み合わせて使います。
なぜそうなのかを知るには、次の行がコンパイルできない理由を理解するとよいでしょう。
const MY_CONST: str = *"Hello, World!";
// the size for values of type `str` cannot be known at compilation time
// the trait `Sized` is not implemented for `str`
リテラル"Hello, World!"の長さはコンパイル時にわかりますが、strとしてはサイズがわからない並びです。
しかし、リテラルへの_参照_(&str)であれば、メモリ上でのリテラルのアドレスと長さを保持する「ファットポインタ」を持ちます。
ファットポインタはサイズがわかるので、次の行はコンパイルできます。
const MY_CONST: &str = "Hello, World!";
文字列スライスへの可変バインディングは、その値を置き換えることはできますが、その場で変更することはできません。
例
let mut my_str = "Hello, World!";
my_str = "Hi!";
let mut my_string = String::from("Hello");
my_string.push_str(", World!"); // there is no equivalent function to modify &str
関数の仮引数を定義するときは、&Stringではなく&strを使うほうが制約が少なくなります。次のコードはコンパイルできないからです。
pub fn main() {
let my_str: &str = "Hello, World!";
say_hi(my_str);
}
fn say_hi(phrase: &String) {
println!("{phrase:?}");
}
// mismatched types
// expected reference `&String`
// found reference `&str`
&strは&Stringに型強制されません。しかし、次のコードはコンパイルできます。
pub fn main() {
let my_string = String::from("Hello, World!");
say_hi(&my_string)
}
fn say_hi(phrase: &str) {
println!("{phrase:?}");
}
&Stringは&strに型強制されます。そのため、仮引数の型に&strを使うと、より便利なことがよくあります。