Telegram Group & Telegram Channel
🧠 Задача на Rust — для продвинутых разработчиков


use std::cell::RefCell;
use std::rc::Rc;

fn main() {
let a = Rc::new(RefCell::new(1));
let b = a.clone();

let c = {
let mut val = b.borrow_mut();
*val += 1;
Rc::try_unwrap(b).ok().unwrap().into_inner()
};

println!("a: {}", a.borrow());
println!("c: {}", c);
}


Что выведет код?

A.
a: 2
c: 2

B.
a: 1
c: 2

C.
Panic at runtime due to unwrap failure

D.
Compilation error due to ownership rules

📌
Ответ:
Правильный ответ: C — Panic at runtime due to unwrap failure

Почему:
Мы создаем a как Rc<RefCell<i32>>, из него делаем b = a.clone() → теперь у Rc два владельца.

Мы мутируем значение через b.borrow_mut(), увеличиваем его на 1.

Затем пытаемся сделать Rc::try_unwrap(b).

⚠️ Rc::try_unwrap требует, чтобы Rc был единственным владельцем. Но у нас всё ещё есть a, то есть ссылка остаётся → unwrap не срабатывает и unwrap() вызывает паник на runtime.


@rust_code



tg-me.com/rust_code/929
Create:
Last Update:

🧠 Задача на Rust — для продвинутых разработчиков


use std::cell::RefCell;
use std::rc::Rc;

fn main() {
let a = Rc::new(RefCell::new(1));
let b = a.clone();

let c = {
let mut val = b.borrow_mut();
*val += 1;
Rc::try_unwrap(b).ok().unwrap().into_inner()
};

println!("a: {}", a.borrow());
println!("c: {}", c);
}


Что выведет код?

A.
a: 2
c: 2

B.
a: 1
c: 2

C.
Panic at runtime due to unwrap failure

D.
Compilation error due to ownership rules

📌
Ответ:
Правильный ответ: C — Panic at runtime due to unwrap failure

Почему:
Мы создаем a как Rc<RefCell<i32>>, из него делаем b = a.clone() → теперь у Rc два владельца.

Мы мутируем значение через b.borrow_mut(), увеличиваем его на 1.

Затем пытаемся сделать Rc::try_unwrap(b).

⚠️ Rc::try_unwrap требует, чтобы Rc был единственным владельцем. Но у нас всё ещё есть a, то есть ссылка остаётся → unwrap не срабатывает и unwrap() вызывает паник на runtime.


@rust_code

BY Rust


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/rust_code/929

View MORE
Open in Telegram


Rust Telegram | DID YOU KNOW?

Date: |

In many cases, the content resembled that of the marketplaces found on the dark web, a group of hidden websites that are popular among hackers and accessed using specific anonymising software.“We have recently been witnessing a 100 per cent-plus rise in Telegram usage by cybercriminals,” said Tal Samra, cyber threat analyst at Cyberint.The rise in nefarious activity comes as users flocked to the encrypted chat app earlier this year after changes to the privacy policy of Facebook-owned rival WhatsApp prompted many to seek out alternatives.

Rust from us


Telegram Rust
FROM USA