This might appear as a noob question - which it is, but I pray, bear with me, I have mostly programmed in languages where I don't need to care that much about memory layouts...
So I have learnt about DST's in Rust, and quoting the reference:
A type with a size that is known only at run-time is called a dynamically sized type (DST ) or, informally, an unsized type
Which I sort of understand. My question now is, more like, okay what does this buy or take from me?
What are the practical repercussion of not knowing the size of a type at compile time? How does it affect a running program etc.
Based on what I know, if i were to answer this question, I will say the difference is that with programs only using types whose size can be known at compile time, one can confidently reason about the upper limit of the memory the program will use. For example if a program only contain this:
fn main() {
fn return_largest_u8(a: u8, b: u8) -> u8 {
if a > b {
a
} else {
b
}
}
dbg!(return_largest_u8(1,20));
}
One can confidently say that the memory requirements is mostly determined by the two u8
argument type and one u8
return type. This can be deduced without even running it.
But another similar program that uses DST like this
fn main() {
fn return_largest_str<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() {
a
} else {
b
}
}
dbg!(return_largest_str("1","20"));
}
One can't make such deduction, because the actual str
behind the &str
which will exit at runtime could be of any size. It could even be on the heap or on the stack. All these cannot be deduced until runtime hence the memory usage of such a program cannot be statically reasoned about.
Will the above submission be true? If not where might I have erred?
Also are there other practical consequences of DST versus sized types than this?