참조로 소유권 차용 (Rust)
11870 단어 Rust
참조에 의한 소유권 차용
예:
struct Foo {
x: i32,
}
fn main() {
let foo = Foo { x: 13 };
let f = &foo;
println!("{}", f.x);
// ①:ここで変数fはドロップします。
// ②:ここで変数fooはドロップします。
}
[실행 결과]
❯ cargo run Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables) Finished dev [unoptimized + debuginfo] target(s) in 1.55s Running `target/debug/variables`
13
예:
fn main() {
let char1 = String::from("hello world");
let len = calculate_length(&char1);
println!("length: '{}' is {}.", char1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
[실행 결과]
❯ cargo run
Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
length: 'hello world' is 11.
참조에 의한 소유권의 가변 차용
예:
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
}
[실행 결과]
❯ cargo run
Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src/main.rs:8:5
|
7 | fn change(some_string: &String) {
| ------- help: consider changing this to be a mutable reference: `&mut String`
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0596`.
error: could not compile `variables`
To learn more, run the command again with --verbose.
예:
struct Foo {
x: i32,
}
fn do_something(f: Foo) {
println!("{}", f.x);
// ここで引数fはドロップします。
}
fn main() {
let mut foo = Foo { x: 13 };
let f = &mut foo;
f.x = 13;
// ここで変数fはドロップします。=> つまり、変な借用もここでドロップします。
println!("{}", foo.x);
// 可変な借用はドロップされているため変更可能となります。
foo.x = 7;
// 変数fooの所有権を関数do_somethingに移動します。
do_something(foo);
}
[실행 결과]
❯ cargo run
Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.33s
Running `target/debug/variables`
13
7
참조 해제
예:
fn main() {
let mut foo = 26;
let f = &mut foo;
// 参照を外し、所有者の値を取得します。
let bar = *f;
// 参照を外し、参照の所有者の値を設定します。
*f = 13;
println!("{}", bar);
println!("{}", foo);
}
[실행 결과]
❯ cargo run
Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.23s
Running `target/debug/variables`
26
13
참조 참조
예:
struct Foo {
x: i32,
}
fn do_something(a: &Foo) -> &i32 {
return &a.x;
}
fn main() {
let mut foo = Foo { x: 42 };
let x = &mut foo.x;
*x = 13;
// 参照を外し、参照の所有者の値を設定します。
// ここで変数xはドロップされます。
// そのため、不変な参照が作成が可能になります。
let y = do_something(&foo);
println!("{}", y);
}
[실행 결과]
❯ cargo run
Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.20s
Running `target/debug/variables`
13
참고문헌
Reference
이 문제에 관하여(참조로 소유권 차용 (Rust)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/yoshii0110/items/46e8c6b4fd67ce9d0adf텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)