10 ms·
As someone who hasn't actually used Rust for anything yet, the example on the root of the site is surprising legible: https://tokio.rs/ https://tokio.rs/ Quest
by koolba 10y ago
As someone who hasn't actually used Rust for anything yet, the example on the root of the site is surprising legible: https://tokio.rs/ https://tokio.rs/
Question for the more knowledgeable Rust folks: Does this code (the echo server example) not handle the situation where the port is already in use? What's the return type of the socket bind in that situation?
EDIT: Wow six responses in as many minutes. I think I've created a new objective measure of how popular a programming language will be!
- hobofan 10y ago`let sock = TcpListener::bind(&addr, &handle).unwrap();` This line tries to bind the port and returns a `Result` type which is then unwraped, which will cause a panic when the port already is in use.
- steveklabnik 10y agoGlad to hear it, especially since this isn't really the code you'd write most often; this is a library that frameworks will use. So it can be even more ergonomic... > Does this code So let sock = TcpListener::bind(&addr, &handle).unwrap(); Here, the bind method [1] will return an error if it can't bind to the port. unwrap will cause a panic to happen. 1: https://docs.rs/tokio-core/0.1.3/tokio_core/net/struct.TcpListener.html#method.bind https://docs.rs/tokio-core/0.1.3/tokio_core/net/struct.TcpLi...
- yammajr 10y agoThis code does not handle the situation - the program will crash. TcpListener::bind(&addr, &handle).unwrap() Rather than raising exceptions, the paradigm in Rust is to return a Response item, which has an Ok and an Err subtype. unwrap() here assumes that the response is Ok and just gives that back the data returned, or crashes if its an error.
- eridius 10y agoNitpick: The program will print an error and abort. It won't crash. It's a "clean" shutdown.
- steveklabnik 10y agoNiptick on your nitpick: it will call the panic hook, then call into the panic runtime, which may unwind the stack or abort. > It won't crash. It's a "clean" shutdown. :+1:
- deleted 10y ago[deleted]
- Crespyl 10y agoThe example code does not handle a failure in that situation. The TCPListener::bind call returns a Result enum, which can have the values Ok(SomeType) or Err(SomeError). The compiler forces you to decide how you want to handle that, for the sake of brevity the example code calls unwrap() which assumes the result is Ok and will either return SomeType or else panic.
- leshow 10y agoIf the socket is already in use the .bind call will fail to unwrap() and the program will panic and exit. It's generally considered bad form to use unwrap() (and by extension panic) in production code, but for examples where you just want to show something it's fine. bind would either return a Option type or a Result type, unwrap is defined for both. edit: Others have looked through the docs and confirmed it's a Result
- sidlls 10y agoThis is actually something about the code samples in Rust docs that irks me a bit. My view is that sample code such as this should be as idiomatic as possible and that means providing a sample demonstrating a typical real use case. So seeing "unwrap" in this context doesn't sit well with me. In fairness, this isn't specific to Rust. I find sample code like this in many projects regardless of language. However Rust is billing itself as a safe systems programming alternative to C and C++. It would help its marketing efforts, in my opinion, by having more robust samples than the competition. And let's be honest: given the competition is C and C++, that's a low, low bar--and this comes from a guy who's about as big a fanboy of those two languages as possible. Edit for more disclaimer: documenting Rust code is a real pleasure. The team has done a stellar job at making documentation an easy thing to do while writing the code. It's already better in most cases than many other projects I can think of.
- steveklabnik 10y agoSo, to be clear, unwrap is safe. It is never going to cause the sorts of memory issues that an uncontrolled crash is. That is, in terms of safety, this is the same thing as explicitly handling the error and then terminating the process. Which is the only real way you're going to handle this error anyway, unless you wanted some sort of retry logic. Which you might!
- threatlock 10y agoBzzzt, wrong! You're on the right track though, fuzz harder
- sidlls 10y agoI agree that in terms of safety it's equivalent. However in terms of how an actual program would be written it's...Less than optimal. I almost never simply allow a panic-like termination in a program like this, if it can be trapped, without doing something else, even if it's just to spit out a log/stdout message with a descriptive reason. Then again the plural of anecdote isn't data, and maybe I'm the oddball here.
- DangerousPie 10y agoOn a related note, how does the `parse()` in `let addr = "127.0.0.1:12345".parse().unwrap();` work? I am assuming that this parses a IP:port string into its components, but it looks like this is just calling a method of the basic String class. So how does it infer what `parse()` is supposed to do?
- carllerche 10y agoRust uses type inference to figure that out. Because `addr` gets passed to `TcpListener::bind` which requires a `SocketAddr`, the type inferencer knows that `addr` should be a SocketAddr and so it all works :)
- Coding_Cat 10y agoparse() is generic over it's return type (which is Result<F, F::Err> where F: FromStr) [1]. The value of which can be inferred. The result of parse().unwrap() is of type F, which means addr is of type 'F'. afterwards when we call `let sock = TcpListener::bind(&addr, &handle).unwrap();` the compiler can infer from the signature of `TcpListener::bind`[2] what F has to be, namely `std::net::SocketAddr` [1] https://doc.rust-lang.org/std/primitive.str.html https://doc.rust-lang.org/std/primitive.str.html [2] https://tokio-rs.github.io/tokio-core/tokio_core/net/struct.TcpListener.html https://tokio-rs.github.io/tokio-core/tokio_core/net/struct....
- koolba 10y agoWhere is string to address parse implementation defined? I took a peek at SocketAddr and see a from_str function. Does that name have special significance?
- Matthias247 10y agoThat code is easy to understand. However I tried to play a little bit with tokio and my first idea was to extend the example to send all bytes 2 times back, which means I tried to avoid the copy helper method. In C/C++ or Go with a blocking socket API that would have been a 5 minute task, but with tokio I was unfortunately quite lost (didn't complete it in 2 hours). Some things that caused headaches were that buffers are consumed by the futures and how to reuse them, getting an infinite read loop running, and trying to compose different types of futures (all the time got errors that different branches have different types, which I finally silenced with using .boxed() everywhere). Maybe I should have tried to implement a custom future with a poll method instead of trying to use composition for that. My intermediate impression is: Basics and the whole idea behind it looks very good and suits Rusts general concepts. However from a productivity point of view it yet can't match the ergonomics of Go or C# with TPL and async/await for IO tasks. But I think the rust contributors are well aware of this and working on some things (async/await like sugar and that impl trait thing which might fix my composition problems).
- eximius 10y agoTo be fair, you often shouldn't be using what is on the home page. More likely, you'll be using something like this: https://tokio.rs/docs/getting-started/simple-server/ https://tokio.rs/docs/getting-started/simple-server/. Perhaps something like that should also be on the homepage to show that, while you can do low-level, it has already scaled up to a higher abstraction for you.
- jessedhillon 10y agoRegarding this line: let addr = "127.0.0.1:12345".parse().unwrap(); Is Rust like Ruby in that devs and library authors can add methods to and redefine built-ins? And that merely including a library can alter the definition of those objects everywhere in your project's code? I'm not trying to start a language war, but IMO that's too bad: this feature is, in my experience, the single largest source for difficult-to-detect errors that characterize the Ruby programming experience, e.g. anything that uses Rails. It also contributes to deep stack traces which are essentially useless, because the departure point from your actual code is some 20+ frames above the site of the error.
- steveklabnik 10y ago> Is Rust like Ruby in that devs and library authors can add methods to and redefine built-ins? It's closer to refinements than monkey-patching, that is, you can, but you must bring the trait into scope for it to work. > And that merely including a library can alter the definition of those objects everywhere in your project's code? No, based on the above rule. We don't want that.
- jessedhillon 10y agoWhich line is including the trait to allow the functionality in this example? (taken from https://tokio.rs/ https://tokio.rs/)
- steveklabnik 10y agoIn this case, it's https://github.com/rust-lang/rust/blob/b9637f79e261d0b90d23bdbce6b0a16d42868bdd/src/libstd/net/parser.rs#L19 https://github.com/rust-lang/rust/blob/b9637f79e261d0b90d23b... So, specifically. Rust has "traits", which, for these purposes, work like Ruby modules. But. Rust has "coherence rules." That is, You can only implement a trait for a type if you defined either the trait, or the type, or both. So, because libstd (well, Rust itself, but you get the idea) all three of FromStr, &str, and SocketAddr, it's allowed to do this. You, in your own package, could not define this, since you wouldn't have defined any of them. In tokio-core, they bring SocketAddr into scope: https://docs.rs/tokio-core/0.1.3/src/tokio_core/net/tcp.rs.html#4 https://docs.rs/tokio-core/0.1.3/src/tokio_core/net/tcp.rs.h... However, I was thinking of a slightly different case when I said that, which is methods. That is, you couldn't call methods unless they've had their traits brought into scope. But parse isn't on a trait; it's defined on `str` itself. In that definition, it also has to bring FromStr into scope. So basically, this is very muddled by the fact that this particular example uses the standard library heavily, which already implicitly brings a lot of things (like &str) into scope for you. External packages don't have that.