Code Answers

Sockets in Rust

Are there any socket or net libraries for Rust? The net page in the standard library documentation seems to only include address-related functions. Solution to answer: The std::net exists for working with sockets. ...

How to do a binary search on a Vec of floats

If you have a Vec you would use the slice::binary_search method. For reasons I don't understand, f32 and f64 do not implement Ord. Since the primitive types are from the standard library, you cannot implement Ord on them yourself, so it does not appear you can use this method. How can you effectively do this? Do I really have to wrap f64 in a ...

How to use Rust’s Peekable

I'm interested in peeking ahead in a character stream. To my understanding, Peekable would be the way to go. I can't quite figure out how to use it. First attempt: fn trawl(pk: &mut I) where I: std::iter::Peekable { loop { let cur = pk.next(); let nxt = pk.peek(); match (cur, nxt) { (Some(i), Some(nxt_i)...

How to catch signals in Rust

I'm trying to write some code that will catch a signal like SIGTERM. I found this and I also found How to handle blocking i/o in Rust, or long running external function calls in general. But in the current Rust version (0.12 nightly) it seems like that std::io::signal::Listener was removed. Did it get put somewhere else? If so can someone point...

How to convert ‘struct’ to ‘&[u8]’

I want to send my struct via a TcpStream. I could send String or u8, but I can not send an arbitrary struct. For example: struct MyStruct { id: u8, data: [u8; 1024], } let my_struct = MyStruct { id: 0, data: [1; 1024] }; let bytes: &[u8] = convert_struct(my_struct); // how?? tcp_stream.write(bytes); After receiving the data, I want to...

What’s the best way to implement a string buffer in Rust

Say I want to do lots of small additions to a string in a row, what's the best way to do this? Is there a data type that's best for this? Solution to answer: Use the String native type, it's designed to be mutable and grow easily. let mut s = String::new(); s.push_str("GET / HTTP/1.0\r\n"); s.push_str("User-Agent: foobar\r\n"); // Etc et...

How to convert Rust strings to UTF-16

Editor's note: This code example is from a version of Rust prior to 1.0 and is not valid Rust 1.0 code, but the answers still contain valuable information. I want to pass a string literal to a Windows API. Many Windows functions use UTF-16 as the string encoding while Rust's native strings are UTF-8. I know Rust has utf16_units() to produce ...

Why are recursive struct types illegal in Rust

I'm trying out random things to deepen my understanding of Rust. I just ran into the following error with this code: struct Person { mother: Option, father: Option, partner: Option, } pub fn main() { let susan = Person { mother: None, father: None, partner: None, }; let john = Person { ...

Returning a closure from a function

Note: This question was asked before Rust's first stable release. There have been lots of changes since and the syntax used in the function is not even valid anymore. Still, Shepmaster's answer is excellent and makes this question worth keeping. Finally unboxed closures have landed, so I am experimenting with them to see what you can do. I hav...

Why does Rust allow calling functions via null pointers

I was experimenting with function pointer magic in Rust and ended up with a code snippet which I have absolutely no explanation for why it compiles and even more, why it runs. fn foo() { println!("This is really weird..."); } fn caller() where F: FnMut() { let closure_ptr = 0 as *mut F; let closure = unsafe { &mut *closure_ptr }; ...

Use of undeclared type or module `std` when used in a separate module

I have the following code: pub mod a { #[test] pub fn test() { println!("{:?}", std::fs::remove_file("Somefilehere")); } } I get errors when I compile this: error[E0433]: failed to resolve. Use of undeclared type or module `std` --> src/main.rs:4:24 | 4 | println!("{}", std::fs::remove_file("Somefilehere")); | ...

How to convert a String into a &’static str

How do I convert a String into a &str? More specifically, I would like to convert it into a str with the static lifetime (&'static str). Solution to answer: Updated for Rust 1.0 You cannot obtain &'static str from a String because Strings may not live for the entire life of your program, and that's what &'static lifetime means. You can o...

What are the Rust types denoted with a single apostrophe

I've encountered a number of types in Rust denoted with a single apostrophe: 'static 'r 'a What is the significance of that apostrophe? Maybe it's a modifier of references (&)? Generic typing specific to references? I've no idea where the documentation for this is hiding. Solution to answer: These are Rust's named lifetimes. Quoting fr...

Is it possible to use `impl Trait` as a function’s return type in a trait definition

Is it at all possible to define functions inside of traits as having impl Trait return types? I want to create a trait that can be implemented by multiple structs so that the new() functions of all of them returns an object that they can all be used in the same way without having to write code specific to each one. trait A { fn new() -> im...

How to get a release build with debugging information when using cargo

The following command $ cargo build produces a non-optimized build with debugging information. On the contrary, $ cargo build --release produces an optimized build without debugging information. Is there a way of producing an optimized build with debugging information? I need this to get meaningful profiling information. Solution to answ...

Case-insensitive string matching in Rust

Is there a simple way to use str::matches case-insensitively? Solution to answer: You can always convert both strings to the same casing. This will work for some cases: let needle = "μτς"; let haystack = "ΜΤΣ"; let needle = needle.to_lowercase(); let haystack = haystack.to_lowercase(); for i in haystack.matches(&needle) { println!...

How to convert a Rust char to an integer so that ‘1’ becomes 1

I am trying to find the sum of the digits of a given number. For example, 134 will give 8. My plan is to convert the number into a string using .to_string() and then use .chars() to iterate over the digits as characters. Then I want to convert every char in the iteration into an integer and add it to a variable. I want to get the final value of...

Are nested matches a bad practice in idiomatic Rust

I have a get_url_content function and don't care about errors (it's just a test). It returns an Option. extern crate hyper; use std::io::Read; use hyper::client::Client; fn get_url_content(url: &str) -> Option { let client = Client::new(); let mut s = String::new(); match client.get(url).send() { Ok(mut res) => { ...