RUST_CODE Telegram 929
🧠 Задача на 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



tgoop.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


Share with your friend now:
tgoop.com/rust_code/929

View MORE
Open in Telegram


Telegram News

Date: |

Although some crypto traders have moved toward screaming as a coping mechanism, several mental health experts call this therapy a pseudoscience. The crypto community finds its way to engage in one or the other way and share its feelings with other fellow members. ‘Ban’ on Telegram 2How to set up a Telegram channel? (A step-by-step tutorial) With the administration mulling over limiting access to doxxing groups, a prominent Telegram doxxing group apparently went on a "revenge spree." In 2018, Telegram’s audience reached 200 million people, with 500,000 new users joining the messenger every day. It was launched for iOS on 14 August 2013 and Android on 20 October 2013.
from us


Telegram Rust
FROM American