VOOZH about

URL: https://qiita.com/quercus491/items/b3631ed40a3042426d27

⇱ RustのWeakについて気付いたどうでもいいこと #weak - Qiita


👁 Image
3

Go to list of users who liked

2

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 3 years have passed since last update.

@quercus491(Make犬)

RustのWeakについて気付いたどうでもいいこと

3
Posted at

RustのWeakについて気付いたどうでもいいこと。

下記のdowngradeの引数に直接&RC::new(値)を渡すコードだとupgrade()で復元した際に値がNoneになる

main.rs
use std::rc::Rc;

fn main() {
 let result = Rc::downgrade(&Rc::new(5));
 println!("result:{}", result.upgrade().is_none())
}

出力結果

fujii@DESKTOP-5KAHK0S:~/test_20210707$ cargo run
 Compiling test_20210707 v0.1.0 (/home/fujii/test_20210707)
 Finished dev [unoptimized + debuginfo] target(s) in 0.29s
 Running `target/debug/test_20210707`
result:true

一旦、RC::new(値)の値を変数に格納するとupgrade()で復元した際に値が保持される

main.rs
use std::rc::Rc;

fn main() {
 let temp = Rc::new(5);
 let result = Rc::downgrade(&temp);
 println!("result:{}", result.upgrade().is_none());
 println!("value:{}", result.upgrade().unwrap());
}

出力結果

fujii@DESKTOP-5KAHK0S:~/test_20210707$ cargo run
 Compiling test_20210707 v0.1.0 (/home/fujii/test_20210707)
 Finished dev [unoptimized + debuginfo] target(s) in 0.31s
 Running `target/debug/test_20210707`
result:false
value:5

関数で&RCを返すとエラーになるんやから、
コンパイル時にdowngradeに変数に格納されていない値をいれたら
エラーにしてくれてもバチは当たらんと思う。

関数の場合

main.rs
use std::rc::Rc;

fn main() {
 let result = Rc::downgrade(test_fn(5));
 println!("result:{}", result.upgrade().is_none());
 println!("value:{}", result.upgrade().unwrap());
}

fn test_fn(param:i32)->&'static Rc<i32>{
 &Rc::new(param)
}

出力結果

fujii@DESKTOP-5KAHK0S:~/test_20210707$ cargo run
 Compiling test_20210707 v0.1.0 (/home/fujii/test_20210707)
error[E0515]: cannot return reference to temporary value
 --> src/main.rs:10:5
 |
10 | &Rc::new(param)
 | ^--------------
 | ||
 | |temporary value created here
 | returns a reference to data owned by the current function

error: aborting due to previous error

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

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

Go to list of users who liked

2
0

Go to list of comments

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3

Go to list of users who liked

2