Just a Blog

[Rust 시험] reassign to borrowed variable 본문

IT, Computer

[Rust 시험] reassign to borrowed variable

wehong 2022. 12. 2. 21:33

테스트 코드

 

fn main() {
    let mut s = String::from("ABCDEF");
    let hello = &s[0..2];
    let world = &s[2..];
    println!("{} {}", hello, world);
    s = String::from("1234567891011");
    println!("s:{}", s);
    println!("{} {}", hello, world); // 이 라인을 삭제하지 않으면 에러 발생
}

 

결과

   Compiling playground v0.0.1 (/playground)
error[E0506]: cannot assign to `s` because it is borrowed
 --> src/main.rs:6:5
  |
3 |     let hello = &s[0..2];
  |                  - borrow of `s` occurs here
...
6 |     s = String::from("1234567891011");
  |     ^ assignment to borrowed `s` occurs here
7 |     println!("s:{}", s);
8 |     println!("{} {}", hello, world);
  |                       ----- borrow later used here

For more information about this error, try `rustc --explain E0506`.
error: could not compile `playground` due to previous error

에러코드 E0506: An attempt was made to assign to a borrowed value

 

그런데 마지막 줄(println!("{} {}", hello, world);)만 삭제하고 's' 출력부분(println!("s:{}",s);)을 살리면 그건 또 실행됨.

AB CDEF
s:1234567891011

 

Comments