녹: 문자열 대 str

16789 단어 rust
이 블로그 게시물에서는 String과 str의 주요 차이점과 언제 무엇을 사용해야 하는지 알아보겠습니다.
String는 힙 할당, 확장 가능한 데이터 구조입니다.
'str는 메모리(힙/스택)에 저장된 변경할 수 없는 고정 길이 문자 시퀀스입니다.



String은 다음과 같이 String::from 메서드 또는 .to_string() 메서드를 사용하여 생성할 수 있습니다.

    // Creating new String variable s1 using String::from method
    let mut s1: String = String::from("Sivakumar");
    println!("{}", s1);

    // Creating new String variable s2 using to_string() method
    let s2: String = "Sivakumar".to_string();
    println!("{}", s2);

    // Calling len() and capacity() methods on string variable
    println!("s1 variable's Length: {}, Capacity: {}", s1.len(), s1.capacity());

    // Calling len() and capacity() methods on string variable
    println!("s2 variable's Length: {}, Capacity: {}", s2.len(), s2.capacity());

    // Adding more data to existing string variable
    s1.push_str(" is working in Singapore!!!");
    println!("{}", s1);


위의 코드를 실행하면 다음과 같은 결과가 나옵니다.

Sivakumar
Sivakumar
s1 variable's Length: 9, Capacity: 9
s2 variable's Length: 9, Capacity: 9
Sivakumar is working in Singapore!!!


str



str 변수는 아래와 같이 문자열 리터럴을 선언하기만 하면 생성할 수 있으며 항상 변경할 수 없습니다.

    // str typed variable can be created as below
    let str1 = "Sivakumar";
    println!("{}", str1);

    // Calling len() method on str variable
    println!("str1 variable's Length: {}", str1.len());


위의 코드를 실행하면 다음과 같은 결과가 나옵니다.

Sivakumar
s1 variable's Length: 9


위에서 알아차렸다면, Rust는 특정 유형의 str 변수를 선언하는 것을 허용하지 않습니다. 대신 Rust가 데이터 유형을 유추합니다.

또한 str 변수에 사용할 수 있는 capacity() 메서드가 없습니다.

str을 변경 가능한 것으로 선언하려고 하면 아래와 같이 경고가 표시됩니다.

    // str typed variable can be created as below
    let mut str1 = "Sivakumar";
    println!("{}", str1);

    // Calling len() method on str variable
    println!("str1 variable's Length: {}", str1.len());

warning: variable does not need to be mutable
  --> src\main.rs:23:9
   |
23 |     let mut str1 = "Sivakumar";
   |         ----^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: 1 warning emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.88s
     Running `target\debug\example.exe`
Sivakumar
str1 variable's Length: 9


문자 조각을 허용하는 함수가 있는 경우 참조된 변수String를 인수로 전달할 수 있습니다.

fn print_len(s: &str) {
    println!("Length of variable: {}", s.len());
}

    // str typed variable can be created as below
    let str1 = "Sivakumar";
    println!("{}", str1);

    // Creating new String variable s1 using String::from method
    let s1: String = String::from("Sivakumar");
    println!("{}", s1);

    print_len(str1);

    print_len(&s1);


위의 코드를 실행하면 다음과 같은 결과가 나옵니다.

Sivakumar
Sivakumar
Length of variable: 9
Length of variable: 9


그러나 String를 인수로 받아들이는 메서드가 있는 경우 str 변수를 전달하면 컴파일러 오류가 발생합니다.

fn print_len(s: String) {
    println!("Length of variable: {}", s.len());
}

    // str typed variable can be created as below
    let str1 = "Sivakumar";
    println!("{}", str1);

    // Creating new String variable s1 using String::from method
    let s1: String = String::from("Sivakumar");
    println!("{}", s1);

    print_len(str1);

    print_len(s1);


산출:

error[E0308]: mismatched types
  --> src\main.rs:34:15
   |
34 |     print_len(str1);
   |               ^^^^
   |               |
   |               expected struct `std::string::String`, found `&str`
   |               help: try using a conversion method: `str1.to_string()`

error[E0308]: mismatched types
  --> src\main.rs:36:15
   |
36 |     print_len(&s1);
   |               ^^^
   |               |
   |               expected struct `std::string::String`, found `&std::string::String`
   |               help: consider removing the borrow: `s1`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0308`.
error: could not compile `example`.

To learn more, run the command again with --verbose.



귀하의 의견을 자유롭게 공유해 주십시오.

즐거운 독서!!!

좋은 웹페이지 즐겨찾기