Hi. Im learning rust and now I have a list of little questions that I would like to ask.
I know that its preferred to ask different questions on different topic but thats a lot of work 
1- What is &* that some times apeear before strings. why just not use & ?
2- imagine we have an int number named var. what difference between these raw pointers
let a = &var as *const i32;
let b = var as *const i32;
I'm having some guesses but I'm not sure
3- why should we use [#no_mangle] before this syntax
extern "C" fn call_from_c()
4-this was mentioned in tutorial. but it didn't include an example. when dynamic dispatch becomes more efficient than static dispatch?
5- is there any way to require a generic NOT to implement some trait?
6- is there any way to use "or" operator on trait bounds? for example generic T should implement either trait sized or send.
7- is there a better way to make threads join main thread? currently I'm assigning spawns result to a variable and then use join function on that variable.
Perhaps one of such cases is when static dispatch comes from monomorphization, and an excessive number of functions generated from the template pollute too much the L1 code cache of the CPU.
1 Like
That syntax is used when you want to convert a raw pointer into a borrow. If a
is *mut int
, you can turn it into a borrow by doing unsafe { &*a }
.
Make sure you know what you're doing wih borrows, though. The Rustonomicon is a great place to get started.
&var
is a borrow on var
, which is an integer. When you cast it to *const i32
, a
is a pointer to an int.
With b
, you're casting an integer to a pointer. If you didn't get that integer by casting from a pointer, you're probably doing something funny (maybe intentionally) with memory.
Because rustc renames your functions to make sure no symbol is duplicated between different crates linked together. C needs the "real" call_from_c
, so we don't want that.
As for the other questions, I would answer "no" to 5 and 6, because you could implement arbitrary logic in there, and the constraints on what traits are required might become unsolvable. With monotone logic (i.e. no to 5 and yes to 6), it might become a possible, but hard problem to solve.
For 7, I don't think you can do better, and I encourage you to try out the rayon crate, which does this for some parallel flows.
1 Like
This is typically to turn a String into a &str
, rather than a &String
. Deref coercion typically do this for you but if you're doing the conversion where deref coercion doesn't take place, then you do it "manually".
1 Like