4 ms·
let my_str = Rc::new(RefCell::new(Box::new(MyStruct1))); Yep, even Rust has better syntax ;). The call is a little more gnarly. Keeping in mind that I don't
by MaulingMonkey 9y ago
let my_str = Rc::new(RefCell::new(Box::new(MyStruct1)));
Yep, even Rust has better syntax ;). The call is a little more gnarly. Keeping in mind that I don't really know rust, my understanding is that this is roughly the equivalent of trying to cast, in C++, shared_ptr<scoped_ptr<MyStruct1>> to shared_ptr<scoped_ptr<MyTrait>>. It's doable, but why the heck would you do it? The C++ equivalent might be:
auto my_str = shared_ptr<unique_ptr<MyStruct1>>(new unique_ptr<MyStruct1>(new MyStruct1));
my_trait_fn(shared_ptr<unique_ptr<MyTrait>>(new unique_ptr<MyTrait>(new MyStruct1(**my_str))));
Which isn't much prettier. Why not instead:
fn my_trait_fn_2(t: Rc<RefCell<MyTrait>>) {
t.borrow_mut().trait_func();
}
fn main() {
let my_str2 = Rc::new(RefCell::new(MyStruct1));
my_trait_fn_2(my_str2.clone());
my_str2.borrow().my_fn();
}
EDIT: Added a C++ example which actually compiles. EDIT x2: Fixed a double free.
- fermienrico 9y agoI admit, I don't know much about Rust. However, I know C/C++ a bit and this drives me nuts: int* foo; // This is a pointer. Understood. int *foo; // How is this allowed!???? Confusing! *foo = bar; // Now you're deferencing. WTF! In the second line, int foo confuses the hell out of me when I am scanning through pages of code. All of this mess could be solved by doing the pointer symbol after the variable name: int foo*; // This is a pointer
- qznc 9y agoThe philosophy in C/C++ is "you declare it how you use it". You declare it with `foo`, you use (assign to) it as `foo`. Likewise for arrays. You declare it `int foo[]` and you use it like `foo[i]`.
- lokedhs 9y agoBecause the * belongs to the variable, not the type. It's more clear with this example, which declares two variables at the same time: int *foo, bar; This declares foo as a pointer to int, and bar as an int. The following, written in the style you suggest, do the same thing but can be confusing, since a casual reader might think that this declares both foo and bar to be pointers to int: int* foo, bar; Someone else commented that C's declarations are designed to look the same as how they are used. This is true, and explains why arrays are declared the way they are, where the brackets come after the variable name: int foo[10]