RANDOM_RUST_DEV Telegram 201
Начинаю регулярную рубрику Rust Tips 🔧

Сегодня - о замечательной функции Cell::from_mut

Она позволяет превратить &mut T в &Cell<T>, что все еще позволяет изменять T, но ее разрешается расшарить
Вот классический пример, где как новичики, так и ветераны спотыкаются о borrow checker

let mut counter = 0;

let mut inc = || counter += 1;
let print = || println!("{}", counter); // cannot borrow `counter` as immutable because it is also borrowed as mutable

inc();
inc();
print();


Передать &mut в inc и одновременно & в print нельзя.

Здесь мы можем использовать магию Cell::from_mut, не изменяя окружающий код.
Обернем ссылку на counter и раздадим в замыкания.


let mut counter = 0;
let cell = Cell::from_mut(&mut counter);

let inc = || cell.set(cell.get() + 1);
let print = || println!("{}", cell.get());

inc();
inc();
print();


🎉 И вуаля - всё работает! 🎉

Бонус для внимательных:
Теперь inc теперь реализует и Fn.
Так что можно тот же трюк использовать что бы передать замыкание, которое что-то мутирует в функцию, которая принимает Fn без Send.



tgoop.com/random_rust_dev/201
Create:
Last Update:

Начинаю регулярную рубрику Rust Tips 🔧

Сегодня - о замечательной функции Cell::from_mut

Она позволяет превратить &mut T в &Cell<T>, что все еще позволяет изменять T, но ее разрешается расшарить
Вот классический пример, где как новичики, так и ветераны спотыкаются о borrow checker


let mut counter = 0;

let mut inc = || counter += 1;
let print = || println!("{}", counter); // cannot borrow `counter` as immutable because it is also borrowed as mutable

inc();
inc();
print();


Передать &mut в inc и одновременно & в print нельзя.

Здесь мы можем использовать магию Cell::from_mut, не изменяя окружающий код.
Обернем ссылку на counter и раздадим в замыкания.


let mut counter = 0;
let cell = Cell::from_mut(&mut counter);

let inc = || cell.set(cell.get() + 1);
let print = || println!("{}", cell.get());

inc();
inc();
print();


🎉 И вуаля - всё работает! 🎉

Бонус для внимательных:
Теперь inc теперь реализует и Fn.
Так что можно тот же трюк использовать что бы передать замыкание, которое что-то мутирует в функцию, которая принимает Fn без Send.

BY Random Rust Dev


Share with your friend now:
tgoop.com/random_rust_dev/201

View MORE
Open in Telegram


Telegram News

Date: |

Earlier, crypto enthusiasts had created a self-described “meme app” dubbed “gm” app wherein users would greet each other with “gm” or “good morning” messages. However, in September 2021, the gm app was down after a hacker reportedly gained access to the user data. The visual aspect of channels is very critical. In fact, design is the first thing that a potential subscriber pays attention to, even though unconsciously. “[The defendant] could not shift his criminal liability,” Hui said. Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. How to Create a Private or Public Channel on Telegram?
from us


Telegram Random Rust Dev
FROM American