(And to those who say they're struggling -- I feel your pain.. but if I could do scala, I can do rust! Most of what I see is "unlearning" Java etc.)
The use case is this -- I'm writing a CPU simulator, so I figured Rust was a learning tool for it. If I were writing in say, Scala, I'd write the following simple class for a physical memory page set.
class PhysicalPage {
storage : Array[Long] = new Array.fill(Long, 0)
}
class PageTable {
pageNumber : Long
Page : Array[PhysicalPage] = new Array[PhysicalPage]....
}
But Rust doesn't work that way, I think I'm supposed to do:
fn new() -> PhysicalPageTable {
// semicolons are mandatory at the end of each statement
let PageNumber = 1024;
// `let`s are mandatory for each variable created
// double-colons are used to call associated methods
// semicolon is used to separate `vec!`'s "element" and "size" arguments
let Page = vec![PhysicalPage::new(); PageNumber];
// last but not the least, you weren't returning the `PhysicalPageTable` you promised with signature
PhysicalPageTable { PageNumber, Page }
}
After that, you'll likely hit an error from the compiler regarding missing Clone implementation on PhysicalPage. Is this correct?
OK -- I'll try those changes. I originally went for an array type, but everything i read says arrays are of limited use? (Again, I have to de-C++/Java myself....)
Oh, and while I'm at it, eventually, I'm going to run into the dependency injection question. I'd have a generic memory provider, which is a super-class of a physical or virtual memory provider. Applications would use the generic provider. If I were in an OO language, I'd do this with the standard inheritance or traits, but does Rust offer things like abstract or virtual function lookalikes? Obviously, since it's not OO, it doesn't have them, but it must have something like it because device drivers really like it -- unless (heaven forbid), I use the old C trick of pointers to cast pointers to cast pointers. Which seems very un-rusty.
Sadly so. Note, however, that array in Rust is not the same thing as array in Java - it has compile-time-defined length, and by default incurs no heap allocation (it must be explicitly Boxed to be put on heap). However, if you can afford the heap allocation, Vec<T> for growable containers and Box<[T]> for non-growable ones will work fine.
Of course it does. Note the emphasis in the quote above, check this chapter of the Book, and, if the static dispatch over generics isn't enough for your needs, check this next.