by SCdF · 8y ago · 0 comments
I really want to like Rust, but I feel like the way they cope with no GC (lifetimes, borrowing) fights me at every turn, and really simple situations in other languages[2] become these intensely painful situations. Every time you think you've worked out how to fix a problem you find while you've fixed that one you've actually created 2 more.
Want to have a data structure of variable size (eg a struct with an Vector in it)? You can't do that, structs have to be fixed size. OK so I'll make it a reference to a Vector. That's great, but now you can't have a factory function because the lifetime goes out of scope. OK so I'll wrap my reference in a Box. OK that's great but now your OTHER reference: a trait (because traits are also of unknown size) is complaining. OK I'll wrap that in a Box as well. Sorry, you can't wrap this trait in a box because before your trait requires implementors to implement copy because at one point you have to use the trait in more than one place and references break the lifetimes and--- THROWS LAPTOP OUT WINDOW
I'm going to keep chipping away at it for a bit longer, but I can feel my interest waning.
[1] Except for the bad docs bit, I really like the docs, and the error messages are definitely earnest in their attempts to help you.
[2] that I'm familiar with, which are no languages that don't auto-GC
-- EDIT --
To everyone taking the first line of my intentional rant paragraph and pointing out it works fine… you're correct, I am mistaken! Let me paste the reply I made to the first person:
---
You're absolutely right. What I really meant was that you can't have Vec<T> where T is a trait without also wrapping that in a box, which for me in turn doesn't work for a bunch of other reasons.
In any case, my point remains the same: it is very challenging-- at least for someone used to just creating data structures and letting GC handle it-- to build code that does what you want, and you spend large amounts of time "fighting" the compiler. I am OK if people wish to peg that on me being stupid or whatever, it doesn't change the core point: it's hard for new people to get into, and if you're wanting there to be less Electron apps and more native apps things like Rust being easy to use seems important for that.
So what you usually do here is have a pointer and a VTable and all that jazz. But there's been a resurgence in interest in putting data into contiguous blocks of memory. Check up on data driven design.
I don't think it's fair to compare GC'd languages to Rust's complexity. At least, compare C to Rust. But still, to be truly fair, weigh the usability differences against the safety differences. There are a lot of trade-offs here and perhaps this isn't the right way for you to go forward, but keep a broad view of the other aspects at play.
This is simply wrong.
> You may very well get the program to compile, but then run into odd bugs which come about because your objects get clipped to the size of the smallest possible (the base class).
That has nothing to do with object sizes. You're describing the object slicing problem
https://en.wikipedia.org/wiki/Object_slicing
The cause of this problem is ignorance and incompetence regarding fundamental aspects of the language.
No! You can rationalize any language problem away with this argument. That's why it's a fallacy with a name: "no true Scotsman" (as in: "no true C++ programmer would let object slicing introduce a bug").
Object slicing is a problem with C++, period.
Sorry, the sole problem is incompetence. Coupling incompetencr with the inability to learn is a problem that no programming language solves. If you insist in shooting yourself in the foot, it makes absolutely no sense to complain that the gun is broken because it doesn't guide bullets away from your foot when you intentionally aim at it.
The object slicing problem is C++ 101. It isn't the language's fault that people who don't know the very basics end up doing mistakes.
Sure, ignorance, whatever. Indeed. That's why I brought it up.
But my greater point still stands: do you want the compiler to catch these things? If so, you have trade-offs.
A vector is a container for homogeneous sequences of fixed-size objects that are stored contiguously. Even if we ignore the slicing problem, don't you see a problem in trying to shove sets of square and rectangular pegs into a container that was specifically designed to support only round pegs of one specific size?
in particular, boost.polycollection is a nice implementation of heterogeneous vectors: http://www.boost.org/doc/libs/develop/doc/html/poly_collecti...
Baloney. In C++ vector<any> or vector<variant> accomplish this task without any problems whatsoever.
structs being classes with public access by default, with default assignment operator behaving the same way as C code would expect.
1. Automatic reference counting is a really good alternative to GC. It takes a little bit more book-keeping, but the performance characteristics are predictable since allocations/frees are handled along the way. Many GC implementations require execution to be halted while the reference graph is traced, which makes it a non-starter for applications trying to deliver predictable real-time performance.
2. Most of the limitations in Rust you're lamenting are there to ensure that your code is safe and performant. Rust requires adapting to very different design-patterns than you might be used to to get these benefits: if something is hard to do in Rust it's probably an anti-pattern with respect to memory performance or safety. Then again if performance isn't your main concern, maybe you don't need Rust.
And of course, once you are multi-threaded, you can more or less forget about "predictable and deterministic" with RC, too.
In contrast, there are real time capable garbage collectors.
The problem with reference counting is that it don't work with recursive structures and counters may overflow. Overflow or reaching some max value and returning runtime error are both problems.
Recursive structures are a problem although in my experience you can usually just alter the ownership rules a bit instead.
FWIW there's a Rust GC library that provides opt-in GC for when you need it. https://github.com/Manishearth/rust-gc
1) GC is lazy, whereas RC is eager;
2) the use of "pure" RC may lead to memory leaks.
Rust is a language where you have to kind of take a step back before working with it to read about the design tradeoffs and why they were made. Certain things you're used to doing with other languages just won't work (e.g. doubly linked lists), and trying to coerce the language into being something it's not leads to you going on one of those frustrating circular rabbit hole journeys you described so nicely above, usually ending up with laptop defenestration.
I'm a week into Rust. I find like you the compiler quite helpful, the docs comprehensive but a bit impenetrable, and the ownership & lifetime system logical on its own terms but very, very unnatural to learn. I don't actually know if its worth it yet.
I am really, really enjoying the O'Reilly Rust book ("Programming Rust"). Maybe sign up for a 10 day Safari trial (free, no card) and give the first few chapters a read. It may help reset you.
That is a succinct explanation of it, yes! Like I can read the documentation and nod along, and the rules seem simple. Actually then remapping your brain and how you want to achieve things seems incredibly challenging
The thing that I have come to appreciate more strongly is that you actually have to think about the same ownership rules in other languages to write bug-free code. Consider e.g. the following Go code:
https://play.golang.org/p/3qfd5B8_ktK
Whether a subslice is still referring to the same array as the slice that it was derived from depends on whether there were any appends that required allocation of a larger backing array. Whether/when this happens is an implementation detail.
Rust prevents this ambiguity by not letting you borrow a `Vec` simultaneously as immutable and mutable (or multiple times mutably). Since the `push` method takes `&mut self`, you cannot have any mutable/immutable slices of the same data.
Another example. If you take a slice of a large array and only use that slice from there on, the slice will (obviously) prevent garbage collection of the backing array [1]. Again, Rust's ownership system prevents such memory leaks, since a slice reference cannot outlive its (owned) `Vec`.
[1] https://forum.golangbridge.org/t/free-memory-of-slice/3713/2
---
I would argue that the cognitive load in other languages is actually higher if you want to write correct code (except perhaps in languages with immutable data structures, such as Haskell), since you have now compiler helping you out. It's just that other languages allow us to cheat when it comes to ownership. For worse or better.
One thing I like to do with a new language is to re-implement a self-contained but non-trivial program that I've built before. I have a few but my favorite is a genetic algorithm which breeds rule sets for a cellular automaton to get the CA to solve some simple computation problems. It's not at all complex, a few hundred lines when done in Python, but it's more than a tiny example. I like it for learning new languages as it touches on various data structures, it's inherently parallelizable, it's not especially bound to any particular programming paradigm, it lends itself to exploring various useful concepts and constructs (function pointers, closures, recursion, etc.), and it is fun and interesting to work on.
So maybe you have something similar, something where you really understand the problem and the solution, freeing your brain to focus entirely on seeing how it would map to Rust.
I'm unclear what you mean here, because Vecs in Rust do have a fixed size. You can see this by using std::mem::size_of on a Vec: for any type, a Vec is three words in size. You can see this documented in the stdlib documentation for Vecs: https://doc.rust-lang.org/std/vec/struct.Vec.html#guarantees
"Vec is and always will be a (pointer, capacity, length) triplet. No more, no less."
So what you're asking for, a Vec in a struct, works just fine:
struct Foo {
v: Vec<i32>
}
let foo = Foo { v: vec![1,2,3] };
Can you elaborate on what trouble you're having?> You're absolutely right. What I really meant was that you can't have Vec<T> where T is a trait without also wrapping that in a box, which for me in turn doesn't work for a bunch of other reasons.
Ah, it sounds like you're using traits as types directly, which is very much discouraged by Rust (especially in conjunction with taking references to those traits). What the language really prefers for you to do is to use traits as bounds on generic types to get rid of the dynamic dispatch and the consequent complications with lifetimes. The only time I'd suggest using traits in the manner you've described is when you need a heterogenous collection, which isn't common in my experience. You've just so happened to stumble across one of the patterns that I most suggest beginners not to do. :P
> In any case, my point remains the same: it is very challenging-- at least for someone used to just creating data structures and letting GC handle it-- to build code that does what you want, and you spend large amounts of time "fighting" the compiler. I am OK if people wish to peg that on me being stupid or whatever, it doesn't change the core point: it's hard for new people to get into, and if you're wanting there to be less Electron apps and more native apps things like Rust being easy to use seems important for that.
I hope that nobody here's making you feel stupid, that would be pretty silly. I've been helping people learn Rust for a long time and it's indeed common for people coming from GC'd/dynamic languages to feel like things are pretty alien (to some degree attributable simply to the differences inherent to systems programming). I as well came from Java/Python and found that there were enough people in the Rust community with that same background that there's no air of elitism suggesting that one ought to feel like a moron for e.g. not knowing what a pointer is. We're all here to help each other, eh? If you ever want to give learning Rust a try again and get stuck, feel free to come ask questions on #rust at irc.mozilla.org or reddit.com/r/rust.
Isn't this basically equivalent to only using templates in C++ code ? and doesn't it kill build times & prevent reusability across different shared objects ?
What do you mean by "prevent reusability"? There's nothing about static vs. dynamic dispatch that prevents code or types from being used across different compilation units.
Can you write an example?
// Define two different types
struct Chihuahua;
struct GreatDane;
// Define a trait with a method
trait Bark {
fn bark(&self);
}
// Implement that method for both types
impl Bark for Chihuahua {
fn bark(&self) { println!("woof") }
}
impl Bark for GreatDane {
fn bark(&self) { println!("WOOF") }
}
Using instances of these types looks like so: let rover = Chihuahua;
let marmaduke = GreatDane;
rover.bark(); // woof
marmaduke.bark(); // WOOF
Now say that you want to write a function that accepts any type that implements the Bark trait. As I mentioned before, there's two ways to do it: the static way, and the dynamic way. Here's what both versions of the function look like: fn speak_static<T: Bark>(dog: T) {
dog.bark();
}
fn speak_dynamic(dog: Bark) { // wait for it...
dog.bark();
}
In the first one, there's a generic type (the "T"), which we have bounded by the `Bark` trait. At compile-time, for each different type that you use with this function it will generate a new copy of the function with "T" replaced with whatever type you actually used (this might seem excessive, but it's crucial for further optimizations).Furthermore, calling this function is trivial:
speak_static(rover); // woof
speak_static(marmaduke); // WOOF
The fact that it's so easy to use these functions is what we mean when we say that Rust "prefers" static dispatch. I'll come back to this in a moment.For the dynamic version, it's different because there's no generics at all. Instead, the function is just taking a normal parameter of type `Bark`. Looks simple, right? In fact, it even looks simpler than the static version! The illusion of simplicity is what makes this so pernicious to beginners. In fact, I've lied to you completely: despite seeming like this should work, it doesn't even compile. That's because, unlike many other languages, Rust doesn't heap-allocate (or "box") things by default. It has to pass function parameters, unboxed, on the stack. And trying to generate a single version of a function whose parameters have unknown size is pretty fundamentally unsafe.
So we have to give this parameter a size. If you're coming from a high-level language, even this is already probably an alien concept (especially since "size on the stack", which is what we care about here, isn't the same thing as "total size of every memory allocation this type might transitively point to").
Anyway, we give this type a size by sticking it behind a pointer. There are many different pointer types we can use depending on one's need. The simplest is probably `Box`:
fn speak_dynamic_box(dog: Box<Bark>) {
dog.bark();
}
Of course, using a `Box` implies a heap allocation, and, since Rust loves speed, it also loves to prefer stack allocation to heap allocation. So what you might actually want to do instead is use a reference, which will let you avoid the heap altogether: fn speak_dynamic_ref(dog: &Bark) {
dog.bark();
}
Now you have a function that takes a stack-allocated reference to a stack-allocated vtable. There's still two pointer indirections to calling `bark()`, which isn't great, but at least we've gotten rid of that heap allocation.It doesn't end there, though. If you try to just call `speak_dynamic_box(marmaduke)`, which is how easy it was for `speak_static`, the compiler will error. That's because `speak_dynamic_box` doesn't take a `GreatDane`, it takes a `Box<Bark>`, which isn't even close to the same thing. So you have to call it like this:
speak_dynamic_box(Box::new(marmaduke) as Box<Bark>);
Not only do you have to box it up manually, but you have to cast it into a trait object. Not pretty, and definitely not worth avoiding generics for.And all this is still understating the restrictions on trait objects. For example, once you cast to a trait object, you can't cast back to the original type (the original type is lost, and if we let you cast back then you'd be able to turn `rover` into a `GreatDane`!). Furthermore, because of various inherent restrictions to how vtables work, not all traits can even be used as trait objects (and trying to explain the technical justification behind these rules, known collectively as "object safety", is enough to make anyone's eyes glaze over). Furthermore, getting back to the `speak_dynamic_ref` example, this only looks as simple as it does (and it doesn't really look simple) because of how simple our example is. If you try to expand this example into anything useful, then you quickly need to really know what you're doing with lifetimes lest you fall into despair.
To summarize, trait objects are an advanced feature that should only be attempted by people who need dynamic dispatch. Rust is designed to favor static dispatch. Don't be fooled by the apparent simplicity of defining functions or structs that take traits as types. In fact, in the near future we'll be introducing a new keyword to make it absolutely clear when trait objects are being used, solely so that new users don't fall into the trap of thinking that they're a simpler path forward than generics.
Lifetimes/borrowing aren't for dealing with no GC, they are for dealing with a number of issues (e.g., shared-state parallelism) that GC doesn't help at all with.
> In any case, my point remains the same: it is very challenging-- at least for someone used to just creating data structures and letting GC handle it-- to build code that does what you want, and you spend large amounts of time "fighting" the compiler.
In a sense, I think that's intentional with Rust. Not unnecessary difficulty, but Rust forces a lot of complexity that would otherwise be easy to overlook and cause runtime bugs to be dealt with upfront by the developer.
For the domain Rust aims at, that probably makes writing correct code easier on balance, but it does make lots of simpler cases harder and higher-overhead than they would be in Python, or even Java, or even in some cases C++, which also isn't GCed, but still leaves a lot of what Rust bakes into static compile-time checks as runtime footguns.
In any case, my point remains the same: it is very challenging-- at least for someone used to just creating data structures and letting GC handle it-- to build code that does what you want, and you spend large amounts of time "fighting" the compiler. I am OK if people wish to peg that on me being stupid or whatever, it doesn't change the core point: it's hard for new people to get into, and if you're wanting there to be less Electron apps and more native apps things like Rust being easy to use seems important for that.
That said, trait objects in Rust are pretty broken in general, so - this is just speculation, but - I think your problem might actually arise from that, and the Vec<Trait> issue is a red herring.
But anyway!: https://doc.rust-lang.org/error-index.html#E0038 <-- these are restrictions on Box<Trait>. The one that screws me is the first one, requiring Sized.
This is a fundamental problem of languages that don't use a managed runtime. You either take the C route and just hope the user did things right or try and enforce it somehow. If you're used to writing GC-code, your problems around understanding object lifetimes are probably going to manifest as 'fighting the compiler' with Rust whereas with C they would manifest as intermittent and hard-to-track segfaults.
If I follow the github in your profile and take the Rust issue you opened, in C that mistake may never manifest except in certain control paths after you've turned off debug mode, and you'd compile code easily but sit banging your head against the wall.
I write a decent amount of Rust and write both C and C++ professionally, and in most cases Rust is drastically easier to write nontrivial code in because it catches all sorts of lifetime issues and has so many QOL improvements.
> What I really meant was that you can't have Vec<T> where T is a trait without also wrapping that in a box, which for me in turn doesn't work for a bunch of other reasons.
You can use any type of pointer to refer to a trait object, not just Box. In particular, you can use &T where T is a trait. The vtable work happening at runtime is the same, but the object can live e.g. on the stack or in a vec somewhere. Of course, if you're using references, you have to convince the compiler that the object is going to stay put for as long as the reference exists, as usual for Rust. When that's not practical, usually a Box or Rc/Arc is the go-to solution. Could you tell me more about what makes Box not work for your use case?
Aside: Trait objects are one of the more complicated features of Rust, and they run into tricky limitations (like "object safety"). It's often people's first instinct to use trait object anywhere they would've used a shared base class in some other language, but that's not usually the best pattern. Using concrete types with trait bounds (`&T .. where T: MyTrait` rather than `&MyTrait`), or inventing a new enum to hold all the types you expect, or even just trying to make ordinary composition work, is usually both easier and more performant.
You can, though due to the extra annotations required I don't suggest that people new to the language try to use trait objects with references. (Hell, I try to keep people new to the language away from trait objects entirely, they're pretty restrictive.)
My understanding is that technically the Vec object itself is fixed size under the hood (a pointer and size field), but as far as I can tell, this is what you're after. It needs no references or boxes.
https://play.rust-lang.org/?gist=8d88b83daa2f389892bfa95c8db...
extern crate rand;
use rand::Rng;
#[derive(Debug)]
struct MyStruct {
v: Vec<u32>
}
impl MyStruct {
pub fn new() -> MyStruct {
let mut rng = rand::thread_rng();
let n = rng.gen_range( 4, 10 );
MyStruct {
v: rng.gen_iter().take( n ).collect()
}
}
}
fn main() {
let ms = MyStruct::new();
println!( "{:?}", ms );
}In what language can you do something like that? In C++, it would compile but anything that you put in the vector would get sliced down to the base type. In Java, everything you put in would get boxed.
To nit though, I think the right thing to do regarding the vector is the tie the vector's lifetime to the struct. (I don't know how exactly to do that syntactically)