11 ms·
Rust means never having to close a socket
- kevingadd 12y agoUsing automated resource management to drive socket (and handle, in general) lifetime is a terrible idea. Sometimes you really, really want to close a handle at a given time. The disposal of associated resources is another matter, and automating that is fine, but leaving a socket open 5 seconds too long is simultaneously 'correct' from a garbage collection perspective and totally, totally not the right thing to do. The key observation here is that things like closing sockets are actual information channels, so tying them to implementation details like object lifetime is a terrible idea. This, concidentally, is why some attempts to tie the lifetime of long-running tasks/threads to object lifetime are a bad idea.
- steveklabnik 12y agoYou can call drop() manually if you want it closed before the end of the scope, no harm, no foul.
- ef4 12y agoThere is no garbage collection in rust. There is no possible "five second gap". Wherever you would have written "socket.close()", in rust you can just say "drop(socket)". The difference is, it takes advantage of the ownership system to statically prove that you won't try to use the socket after close. Or just let it go out scope and it will be dropped immediately. NOT eventually garbage collected.
- monocasa 12y ago> Wherever you would have written "socket.close()", in rust you can just say "drop(socket)". The difference is, it takes advantage of the ownership system to statically prove that you won't try to use the socket after close. Does a drop somehow say something to the type system as well, disallowing reads and writes afterwards? I'm new to rust, sorry if that's a stupid question.
- pcwalton 12y ago> Does a drop somehow say something to the type system as well, disallowing reads and writes afterwards? Yes.
- Leon 12y agoThe other poster says it proves operations won't happen again - does it do both?
- kibwen 12y agoYep! The owner of a thing can do the following: 1. Give ownership away to something else. 2. Free the object at the end of the scope. In order to do anything to the object, you give up ownership to the function that does it (which can then give it back, if it doesn't need ownership of the value any more and doesn't want to free it itself). This even applies to the `drop` function, which just takes ownership and then does nothing whatsoever to the passed-in value, allowing it to go out of scope immediately. So once you've called `drop(foo)`, you no longer own the value and so can't give it away to any reading or writing function, and you can't drop it for the very same reason.
- hrjet 12y agoCurious to know why `drop` isn't called automatically by the compiler as soon as possible (since the type system already seems to know it is safe). Is there a trade-off involved here?
- kibwen 12y agoFreeing resources as soon as humanly (computerly?) possible will optimize your memory usage, but can actually be worse for execution speed. If you're willing to use slightly more memory, it's generally faster to free memory in coarse chunks than one-thing-at-a-time. So even though Rust can conceivably free memory sooner, it might as well defer freeing until the end of the scope, since it can prove that that's safe. To take this to the logical extreme, see this awesome post from Walter Bright, where he doubles the speed of the D compiler by providing a custom malloc implementation that never frees, leaking all memory until the end of the process: http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over-75/240158941 http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over...
- Leon 12y agoI have not used Rust before; does working with statistical analysis of runtime environments hinder debugging? In a multithreaded environment - does it pause the world for its runtime analysis or are there locks on shared resources representing ownership of individual objects, or does it do copies on writes of resources for idempotent operations as the references are moved around environment for lockless operations?
- steveklabnik 12y ago> does it pause the world for its runtime analysis The borrow checker is _entirely_ at compile time.
- ben0x539 12y agoTo be fair, resource disposal is sometimes "delegated" to runtime. But it's always a local concern, like a reference counter for a shared resource, or a mutable `Option<R>` value that can have the R resource taken out of it or put back into it dynamically. There's no creepy overarching runtime system that tracks individual objects from a distance.
- steveklabnik 12y agoYes, it's hard to figure out which way to talk about it. Rc<T> isn't really part of the borrow checker... it technically subverts it to do its own thing internally.
- ben0x539 12y agoI wouldn't really consider the whole ownership thing or specifically the mechanism that inserts destructor calls at the logical end of a value's lifetime part of the borrow checker either, but I dunno how the implementation is laid out.
- solipsism 12y agoJust to be clear (and to check this myself -- I'm just starting to learn Rust), a five second gap is actually possible right? Say I use a socket, stop using it, don't call drop(socket), and I don't leave the scope for 5 seconds because I'm busy doing something.
- ef4 12y agoYes, you are correct. What I was trying to explain is that the timing is deterministic and immediate. People are used to unpredictable GC and rightly don't want to trust it with thing like this.
- ben0x539 12y agoYeah, if you hold on to the thing in your scope, it won't go out of scope and won't be disposed of.
- tomp 12y agoI agree. Having files and sockets close automatically is a bad pattern. Ideally, in a language with linear types, the compiler would notify you of all resources that you didn't properly dispose of when they go out of scope - so, unless you return the handle or call `close(f)` at the end of the function, you'd get a compiler error. The compiler could also auto-insert `close()`/`dispose()` methods when they go out of scope, as is implemented in Rust using the Drop trait. I don't know if Rust supports forcing explicit deallocation, but even if it doesn't, it's still an improvement compared to most GC-d languages.
- dkhenry 12y agoIf I understand the borrowing and lifetime mechanisms of rust it would be trivial to have it say anything that has a lifetime that is active at the end of a scope is a compiler error. It would almost be like how in c++ you can disable copying by setting all the copy constructors to delete and then the compiler will tell you if your accidentally making copy's of objects.
- tomp 12y agoI agree, it would probably be trivial. It's mostly a language/library design issue, not a type-systems research problem.
- steveklabnik 12y agoYou're talking about linear types, Rust implements affine types. They're very similar.
- justinsb 12y agoC++11 introduces unique_ptr, which has a lot of the same safety characteristics. Rust's syntax does seem much nicer, though.
- pcwalton 12y ago> C++11 introduces unique_ptr, which has a lot of the same safety characteristics. Sure, other than not actually being safe (UB resulting from use after move of unique_ptr being an obvious one; there are many others).
- justinsb 12y agoGood point! Safe if used very carefully, perhaps - like most of C++.
- Dewie 12y agoRaw pointers are safe if used very carefully... :)
- wycats 12y agoFor those who might have been wondering, "UB" means "undefined behavior".
- Animats 12y agoRight. C++ used to have auto_ptr, which did roughly the same thing, but didn't quite get it right. Transferring ownership was always iffy. There were, I think, three standardized versions of auto_ptr, all bad. Now there's unique_ptr, which is supposed to be better. The lesson of C++ is that you can't bolt on safety by using templates to paper over the underlying mess. The mold always seeps through the wallpaper. The usual problem is that at some point you need raw pointers to call some API. If you can get raw pointers, the abstraction has to have a leak.
- crantanplum 12y agoWhat part of that is undefined? When you move the pointer, the original becomes null..
- rcthompson 12y agoSo in the first example, "from_file" is never used after the first call to "io::util::copy". Is Rust smart enough to realize that this is the last use of "from_file" and release it right then, or does it wait until it goes out of scope at the end of the function?
- steveklabnik 12y agoCurrently, borrows are lexical. We don't want them to be that way forever. https://github.com/rust-lang/rust/issues/6393 https://github.com/rust-lang/rust/issues/6393
- wycats 12y agoTo be more specific, automatic dropping will likely always be scope-based. In the rare case where you need to drop something before its owning scope completes, you can explicitly use `drop` as people have said downstream. Borrows are a different story. Especially with mutable borrows (which are basically a static lock on the value), the current lexical restriction is too coarse-grained. There are always workarounds, but it will be nice when it's fixed :)
- rcthompson 12y agoIs there a specific reason for automatic dropping to be scope-based? Is it because dropping things could have side effects (e.g. closing a filehandle) and scope-based dropping makes it easy for someone looking at the code to determine when these side effects will occur?
- zokier 12y agoThere is ongoing discussion about this, eg here: https://github.com/rust-lang/rfcs/pull/239 https://github.com/rust-lang/rfcs/pull/239 (related reddit thread: http://www.reddit.com/r/rust/comments/2gs85u/rfc_allow_compiler_to_drop_unneeded_objects/ http://www.reddit.com/r/rust/comments/2gs85u/rfc_allow_compi... )
- illumen 12y agoFor files python[0] does not need an explicit with to close the file. It gets closed when references reach zero. [0] For the pedants repeating each other in the replies... Where by python, I mean the implementation that 98% of people use, called python, which the competition calls CPython. Yes it is a great feature of the implementation, like the deterministic memory management through reference counting.
- Wilduck 12y agoThis is currently true in CPython, but is not necessarily true in other implementations. It's good hygiene in python to use a `with` statement for this reason, as well as helping to enforce that you don't accidentally hold on to a reference, and keep the file open. I think that context managers in python are generally a very nice abstraction over these sorts of concepts, and it's cool to see how Rust is handling these problems very cleanly.
- wycats 12y agoWhat happens if there's a cycle? It will get closed when the cycle is finally collected. You can rely on a GC (and refcounting + a cycle collector is absolutely a GC) to finalize your resources for you, but it is quite difficult to reason about when the file will eventually be closed. Also, the reference counting semantics of CPython are implementation-specific. From the PEP that introduced `with`: > Note that we're not guaranteeing that the finally-clause is executed immediately after the generator object becomes unused, even though this is how it will work in CPython. This is similar to auto-closing files: while a reference-counting implementation like CPython deallocates an object as soon as the last reference to it goes away, implementations that use other GC algorithms do not make the same guarantee. This applies to Jython, IronPython, and probably to Python running on Parrot.
- illumen 12y agoCPython is the implementation that 98% of the market uses, but you are partially correct for that other 2%. You are also wrong for CPython which does NOT require the garbage collector to be on, and DOES release the file in a deterministic way. Simply, the article is misleading with regards to python.
- dengnan 12y agoAnyone has good learning resources about rust? I find it's a very interesting language but the document on its web site is so limited. Many topics are not covered or explained in vague terms. The new guide is a good starting point but still needs some improvement.
- shmerl 12y agoThis is WIP: http://doc.rust-lang.org/guide.html http://doc.rust-lang.org/guide.html
- steveklabnik 12y agoIts WIP status is 'basically done, just editing and having tons and tons and tons of people read it to catch small things' :)
- shmerl 12y agoThat's good!
- doe88 12y agoFor newcomers I think the documentation is quite good. But where I think there is currently a big problem it is for intermediate / advanced level documentations, it is very limited. Sometimes you'll read some code and say to yourself "I didn't know I could do that, cool". In order to grasp more knowledge you'll have to read RFC, commit logs, issues, and source codes, but because it certainly is not your main job it's really time consuming.
- steveklabnik 12y agoYup. I've been working from the bottom up, so I'd agree with your analysis wholeheartedly. As the rest of the Guides fill out, it'll get better.
- doe88 12y ago
- spion 12y agoIf borrowing is the default, why does it require additional syntactic noise? Why isn't transfer achieved by adding sigils such as "&"?
- kibwen 12y ago1. Familiarity to C++ programmers, for whom taking a reference via `&` is a familiar operation. 2. There are two different kinds of references: `&` is immutable and `&mut` is mutable. One way or the other you'd need some sort of differentiation. 3. Borrowing, though crucial to the idea of Rust, is still less fundamental than ownership. You can have a language with ownership and without borrowing (indeed, this is how most prior languages with ownership work). But you can't have borrowing without tracking ownership.
- wycats 12y agoAlso, there are a whole host of very common types (integers, etc.) that actually want to be passed by value and copied. There's no point in making a pointer to an integer and then dereferencing the pointer in the callee when an integer fits into the same amount of space as a pointer in the first place. Very simple types (without heap pointers or destructors) can be passed by value and efficiently copied. You end up with a bit of an intuition for "value types" (simple types whose identity is bound up in the shallow memory that they contain). In other GC'ed languages, there is a fixed set of these kinds of values (often called "primitives"). In Rust, any simple user-specified type can be a "primitive".
- Animats 12y agoIf something is immutable (and doesn't own something else), it doesn't matter whether it's passed by value or reference. That's a decision the compiler can, and should, make, as an optimization decision. In Modula, where pass-as-read-only was the default, small items were passed by value and large ones by reference. "Small" is a CPU-dependent optimization and should be left to the compiler, not "user intuition". The default should be pass as read-only reference. If you want a copy of something, you should have to explicitly make one. If you want write access, you should have to say so. Rust has all the right concepts, but the defaults aren't in the safest direction. The experience of "const" in C/C++ teaches us that they should be.
- bobfunk 12y agoAwesome post. Best explanation I've seen so far how Rust's resource management. Always impressed with Yehuda's ability to explain complex techniques and abstractions clearly. Having the compiler eliminate resource leaks is really, really handy. This is one thing that's very easy to get wrong in go. Will be interesting to see how much of a cost the upfront typing has during quick prototyping or explorative programming, but its great to see this kind of type system make it into something that's well on track to becoming a mainstream programming language.
- hubert77 12y agoreally interesting stuff. small typo. fn person(person: &Person) -> &str { ... } should be: fn first_name(person: &Person) -> &str { ... }
- spullara 12y ago"Rust achieves both of these features without runtime costs (garbage collection or reference counting), and without sacrificing safety." If it is freeing everything at the scope boundary it is incurring a huge runtime cost relative to garbage collected languages. GC scales with the number of live objects during GC while this scheme scales with the number of allocated objects. It is far more predictable than GC but I don't believe that it isn't more expensive.
- wycats 12y agoI'm a little bit confused. Every object that gets allocated has to be freed at some point. That cost is the same no matter how the memory is managed. Are you talking about an additional cost beyond "freeing memory that was allocated"?
- krig 12y agoIt sounds like they are talking about a semi-space collector, which I can imagine might in theory be faster than scoped allocation since allocation is a simple pointer bump (just like stack allocation) but when garbage collecting you only have to traverse the live set. However, semi-space collectors can't collect non-memory resources without additional metadata, and they have a memory overhead of at least 2x the maximum live set. I have a hard time imagining even a semispace collector outperforming stack allocation. Of course if your program is short-lived you can just allocate a sufficiently large heap, pointer bump the whole way and free all non-memory resources on program termination, which ought to be cheaper (but probably not that much in practice due to cache effects).
- wycats 12y agoIn Rust, you often use stack allocation, which, as you pointed out, is much more efficient. There's some heap allocation in Rust, but in my experience it's actually a minority of all allocations. Rust also has an Arena library (http://doc.rust-lang.org/0.11.0/arena/index.html http://doc.rust-lang.org/0.11.0/arena/index.html), which can be used for cases where you know that you have enough memory for a given operation and are willing to throw out the entire thing when the operation (or program ;) ) is done.
- mwcampbell 12y agoI agree that automatic, deterministic resource management (as opposed to GC plus a dispose pattern of some kind) is highly desirable. But I think for the vast majority of projects, I would prefer automatic reference counting with the occasional weak reference to break cycles, particularly if that were the default for the language. I can appreciate that being explicit about resource ownership is an advantage in situations where one needs to absolutely minimize performance overhead. But for most applications, I think a system of ownership and borrowing like Rust's would just add extra cognitive load for the programmer for no appreciable gain. Of course, Rust isn't a language for most applications AFAIK; it's a systems language for performance-critical infrastructure like Servo. And Rust is probably not a language for blub programmers. But I think this blog post is absolutely right about the problems with GC plus a system for disposing of resources. It sucks that mainstream, blub-friendly language have mostly chosen GC over reference counting; I think automatic reference counting provides the right set of trade-offs for most applications.
- steveklabnik 12y agoYou can do that if you want, just use the Rc<T>/Arc<T>/Weak<T> types. That said, you're right: if you don't need Rust's strengths, the tradeoff may not be worth it.
- mwcampbell 12y agoI know Rust has RC pointers. But I'm guessing a Rust programmer would still have to understand ownership and borrowing, since the standard library and third-party libraries use those concepts. I think what I'd really like is something like C# and the .NET base class library, but AOT compiled to native code and using automatic reference counting, with some way to indicate weak references. I know that neither GC nor reference counting quite reaches the level of "don't make me think" when it comes to resource management, but given a choice between explicit resource disposal and the occasional weak reference annotation, I think I'd choose the latter. Anyway, enough ranting from me for now.
- steveklabnik 12y ago
- kazinator 12y agoIn garbage collected languages with macros and an "unwind protect" operator, we avoid explicitly closing files and other resources using with scoped binding constructs implemented by macros. (with-locked mutex ;; ... critical section ) ;; mutex is released here
- wycats 12y agoI specifically address this pattern towards the end of my post (it's essentially the same pattern as Ruby's approach).
- ben0x539 12y agoThat only works if the lifetime of a resource is a lexical region, right?
- agumonkey 12y agoGood question. I wonder if there was some Lisp with linear logic that would allow lexical and ~borrowed (sorry if I misuse the term) resources management.
- malisper 12y agoIt shouldn't be very hard to create a basic ownership system. Here is a version I just wrote, which works by defining a new version of "defun" that uses dynamic variables to keep track of ownership: (defvar *transferring* '() "Objects which are going to be transferred from one owner to another.") (defvar *resources* '() "The resources which need to be freed when the current procedure is done.") (defmacro new-defun (name args &body body) "Define a procedure which will have ownership over the resources it creates using any of the 'new' procedures. `(defun ,name ,args (let ((*resources* *transferring*)) (setf *transferring* '()) (unwind-protect (progn ,@body) (mapcar #'free *resources*) (mapcar #'free *transferred*))))) ; These are resources which were supposed to be transferred by weren't due to an error. (defun transfer (resource) "Transfer ownership of a resource from the current one to the next procedure called which can accept ownership." (push resource *transferring*) (setf *resources* (remove resource *resources*)) resource) (defun new-open (&rest args) "Open a file whose owner is the first procedure up the stack which can accept ownership." (let ((file (apply #'open args))) (push file *resources*) file)) All that is needed now is a method "free" which will free any given resource. With this, any resource allocated with a "new" procedure (the only one I wrote was "new-open") will by put under ownership of the last procedure on the stack which was defined with "new-defun". Transfer between owners can take place by using "transfer". The best part is that more facilities are easy to build on top of this. The "drop" procedure would be trivial to add. The only problem I can see here is that there may be some issues if "free" throws an error, since "unwind-protect" doesn't protect the cleanup-forms. This should be fixable by just wrapping every call to "free" with "ignore-errors".
- yoodenvranx 12y agoDoes anybody know if Rust will reach all those nice goals or are there some theoretical / comp sci reasons why it might fail?
- Rusky 12y agoEverything in this article already works (and has for quite some time). The author is using it in production.
- yoodenvranx 12y agoYes, I know it is working for quite some time, I was more wondering if there are some hidden inherent problems lurking below the surface or if the theory behind rust is sound, e.g. some corner cases where it breaks down or result in undefined behaviour.
- steveklabnik 12y agoEverything in the post works today. This doesn't mean that Rust is absolutely perfect. There's tons of stuff that is awkward to express, and tons of more features that would be nice to have. But the core all works, and works well.
- crazychrome 12y agoGreat post. I think it's the first I've ever read about Rust clearly clarifies the owner of a ownership is scope. It may sound ridiculous but all other talking about ownership without mentioning who is exactly the owner.
- andrewflnr 12y agoYeah, I sort of had to figure that out for myself too. Everyone talks about ownership being recursive without specifying the base case.
- jaekwon 12y agoThis works well for system resources, but what about custom objects destructors?
- steveklabnik 12y agoYou implement the Drop trait yourself, and it Just Works.
- martin1975 12y agoSlightly off topic, how do I go about doing any meaningful GUI programming in Rust? Do Qt bindings exist for Rust? How easy or difficult is it to create such bindings? It's a great language but if it doesn't have a bridge of some sort to the existing legacy code (C++ included), then it's no good to me.
- shadowmint 12y agoAs someone who's been using (and really liking) rust for about 6 months, there are two things in this article which are, I'd say, 'common misconceptions' about rust: One of the coolest features of Rust is how it automatically manages resources for you, while still guaranteeing both safety (no segfaults) and high performance. In rust there are two types of code. 'safe' and 'unsafe'. The above is only true if your entire code path contains only safe code. NOT, if you only write safe code. That is, if you write entirely 100% safe code, and use some library that uses 'unsafe' code at a low level (this is very common; for example, an C binding or memory optimization), then rust does NOT guarantee safety. Furthermore, there is no way to know if your code path includes unsafe code. Rust is relatively safe; it's just not totally safe. Using rust does a reasonable job of protecting you from segfaults most of the time; but it's not a silver bullet. As soon as the program stops using the resource, its cleanup logic gets invoked. ... Because only one scope owns an object at a time, you can tell just by looking at it which objects will be destroyed when it's done executing. This isn't always necessarily true. Rust uses 'drop flags', which are extra bytes at the end of struct instances in memroy, to track objects and keep meta information about them to determine if they should be dropped. At the end of scope when the drop checker runs it checks against these drop flags to determine if an object should be dropped or not. (For example, if a closure captures a variable it may no be dropped at the end of the scope it would normally have been dropped in). There seems to be this myth that resource deallocation in rust is magically determined at compile time and the has 'zero cost'; it's simply not true. There is a runtime cost to the drop checker; it's not particularly large, but it's certainly not just a sequence of drop operations. Don't get me wrong; I really enjoy rust, and I like it a lot. ...but those two ideas pop up repeated in discussions about it, and they're not exactly correct.
- wycats 12y ago> In rust there are two types of code. 'safe' and 'unsafe'. The above is only true if your entire code path contains only safe code. I think this is actually a misconception. In every high-level language (Ruby, Python, etc.) there are APIs for interacting with low-level code. These APIs (C bindings and FFI) are unsafe, and are in the path of virtually all high-level code. It is the responsibility of somebody implementing a C binding for Ruby to ensure that the publicly exposed API is safe. If you use `nokogiri` in Ruby and get a segfault, that is a bug in nokogiri. It is not an indication that Ruby is unsafe. Similarly, the "safe" dialect of Rust is Rust. Rust provides a low-level binding to unsafe code via the unsafe dialect that is philosophically equivalent to the FFI API or C bindings in Ruby. If somebody uses the low-level binding and exposes a Rust library that segfaults, there is a bug in that binding, full stop. I think this is very important. If you use regular Rust code with the expectation that "anyone in your path may cause you to segfault", something has gone very, very awry in the ecosystem. This is not an expectation in other high-level languages when people write low-level libraries with unsafe code in them, and it should not be an expectation in Rust. > Rust uses 'drop flags', which are extra bytes at the end of struct instances in memroy, to track objects and keep meta information about them to determine if they should be dropped This is in the process of being eliminated (see https://github.com/rust-lang/rfcs/pull/320 https://github.com/rust-lang/rfcs/pull/320). I didn't mention it because it's runtime overhead that will not be present shortly, and certainly by the time 1.0 is reached later this year.
- m0th87 12y agoThere's a couple bugs in the sample code: `is_thirties` won't compile because it's missing a type declaration, and the `person` function should be called `first_name`.
- kolev 12y agoI love Rust, but really can't use it at work until it has a fully-featured AWS API. I had similar issues trying to use D and Dart in the past. Go doesn't have an official SDK either and although goamz isn't complete, the situation there is much better.
- walrus 12y agoYou could start writing it.
- kolev 12y agoMaybe in a parallel universe where I have time for these kind of things... It shouldn't be too hard to reverse-engineer botocore, use the these JSONs here [1], and generate code based on them. [1] https://github.com/boto/botocore/tree/develop/services https://github.com/boto/botocore/tree/develop/services
- chaotic-good 12y agoIn Rust, unlike in garbage collected languages, you never1 explicitly close or release resources like files, sockets and locks GC languages is trying to emulate machine with infinite memory so you don't need to bother yourself with _memory_ management. It's not compatible with rust's resource management system that manages resources and treats memory as another type of resource. The same is true for C++ BTW, in good C++ code you never release resources by hand and use ownership for this (RAII).