t_wの輪郭

Feedlyでフォローするボタン

String&strの結合

fn main() {
    let s1 = String::from("Hello, ");
    let s2:&str = "world!";
    let s3 = s1 + &s2;      // s1はs3へ所有権が移動し、使用できなくなる
    println!("{}", s3);     // Hello, world!
}

+

2022/2/19 14:59:00

StringStringの結合

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;      // s1はs3へ所有権が移動し、使用できなくなる
    println!("{}", s3);     // Hello, world!
}

参照外し型強制という仕組みによってうまく動いているらしい。
勉強したら追記する

&str&strの結合

+演算子では不可能。formatを使おう。

fn main() {
    let s1:&str = "Hello, ";
    let s2:&str = "world!";
    let s3 = s1 + &s2;      // error!!!
    println!("{}", s3);     
}
error[E0369]: cannot add `&&str` to `&str`
 --> src\main.rs:4:17
  |
4 |     let s3 = s1 + &s2;      // error!!!
  |              -- ^ --- &&str
  |              |  |
  |              |  `+` cannot be used to concatenate two `&str` strings
  |              &str
  |
help: `to_owned()` can be used to create an owned `String` from a string reference. String concatenation appends the string on the right to the string on the left and may require reallocation. This requires ownership of the string on the left
  |
4 |     let s3 = s1.to_owned() + &s2;      // error!!!
  |              ~~~~~~~~~~~~~

Stringu32の結合

+演算子では不可能。formatを使おう。

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = 1234;
    let s3 = s1 + &s2;      // error!!!
    println!("{}", s3);     
}
error[E0308]: mismatched types
 --> src\main.rs:4:19
  |
4 |     let s3 = s1 + &s2;      // error!!!
  |                   ^^^ expected `str`, found integer
  |
  = note: expected reference `&str`
             found reference `&{integer}`