3 ms·
That can be a problem. Some common C/C++ idioms do not translate to Rust. In particular, a function which creates and returns an object is difficult to express
by Animats 11y ago
That can be a problem. Some common C/C++ idioms do not translate to Rust. In particular, a function which creates and returns an object is difficult to express in Rust. In Rust, you have to create the object before the call, then pass it to a function to be filled in. Either that, or go with a reference-counted type.
- comex 11y agoAre you referring to objects that contain inner pointers? Otherwise you can just return T or Box<T>.
- Manishearth 11y agoYeah, at some level of complexity you do start needing some Cell/RefCell/Rc, but it's not much.
- ryeguy 11y agoWhat makes you think you can't create and return an object? This is how every constructor function in rust works.
- shadowmint 11y agoI believe this is referring to '...and keep a mutable reference to it' ie. A singleton, and many overseer style observe-and-update-on-change data binding patterns. Basically, shared ownership is pretty central to many C++ patterns, which means they translate poorly into rust.
- akiselev 11y agoRust functions return expressions, not objects and it is entirely up to the compiled code at the function call site whether it is placed in the stack or the heap, and whether the function code is inlined or not (thus expanding the stack allocated in the parent function). ::new doesn't create a structure, it just returns the expression that is supposed to initialize the struct in memory, which the compiler writes to the stack or to the heap through the Box constructor. If you look at the antipattern example in the "Returning Pointers" section of the Rust book [1], you'll see how you are supposed to handle object creation (the box syntax is the same as Box::new) in a Rustic way [1] https://doc.rust-lang.org/book/box-syntax-and-patterns.html https://doc.rust-lang.org/book/box-syntax-and-patterns.html