3 ms·
How would you do the equivalent of this in Rust? auto on_heap = std::make_unique<MyType>(...); function_that_accepts_lambda([obj = std::move(on_heap)]() {
by hendzen 10y ago
How would you do the equivalent of this in Rust?
auto on_heap = std::make_unique<MyType>(...);
function_that_accepts_lambda([obj = std::move(on_heap)]() {
obj->bar(...);
})
- steveklabnik 10y agolet on_heap = Box::new(...); function_that_accepts_lambda(move || { on_heap.bar(); }); This is sort of what kibwen was mentioning: move is a single annotation that overrides everything to capture by value rather than have it inferred.
- hendzen 10y agoWhat if you want to move some things, but copy others? e.g. auto shared = std::make_shared<MySharedType>(...); auto unique = std::make_unique<MyOwnedType>(...); function_that_accepts_lambda([shared, u = std::move(unique)] { shared->foo(...); u->bar(...); }); // Outer scope can still use shared. shared->foo(....);
- vvanders 10y agoIf the type implements Copy they'll be implicitly copied when moved into the Rust closure(I think). Or you can declare a scope var and clone() manually.
- steveklabnik 10y agoI am 99% sure this is identical: let on_heap = Box::new(...); let shared = Arc::new(...); let s = shared.clone(); function_that_accepts_lambda(move || { on_heap.bar(); s.foo(); }); We have to make the extra s binding. Also, my sibling is correct that Copy types will just be copied, not moved.