# Tag Info

31

Learn to love rustfmt. For example, the Rust standard is 4-space indents. Learn to love Clippy, which can show you the more idiomatic way to iterate over a collection: warning: it is more idiomatic to loop over references to containers instead of using explicit iteration methods --> src/main.rs:43:18 | 43 | for x in times.iter() { | ...

26

I think that match is better, you just do not know how to cook it ;) fn main() { for i in 1..102 { match (i%3, i%5) { (0, 0) => println!("FizzBuzz"), (0, _) => println!("Fizz"), (_, 0) => println!("Buzz"), (_, _) => println!("{}", i) } } }

23

C would have allowed you to just ignore errors and pretend everything was good. A naïve cat would be very short, but rather unreliable also. A well‐written cat will go and use all the error codes that are returned to produce a useful result. Python and similar languages would raise exceptions in these cases, leading to you getting tracebacks in case of ...

23

Cargo Fmt There's a very common tool accessible through cargo which can format all of the code in your project according to Rust's official style guide. Many major open source Rust libraries use this tool (and even enforce it through CI on pull requests), which you can access through cargo fmt. You can also customize its output using a .rustfmt config file. ...

16

imports Your imports should be compressed: use std::io::{self, Read, Write}; Although it might be better to use the io prelude: use std::io; use std::io::prelude::*; I prefer the former for its explicitness. match vs if let match io::stdin().read_line(&mut s) { Ok(_) => {}, Err(err) => { println_stderr!("{}", err.to_string());...

16

Correctness of the solution On reflection, I'm not sure either the C++ or the Rust code solves the problem as stated. I'm not completely sure I understand the shoe shine shop model so I may be wrong. Here's what it looks like the code does: you generate a bunch of random events of all kinds, and order them in time. Then you process the events one by one ...

15

I'm going to treat this as a code review question where the goal is to figure out how to write high-performance I/O code in Rust. There are two critical steps to speed up Rust I/O: Make sure the optimizer is turned on. Rust loops have terrible performance in debug mode. Turning the optimizer on should probably get you near 25 MB/sec or so, at least in my ...

12

Examples have first-class support in Cargo. Place them in a directory examples next to src. They can then be run with cargo run --example foo. They will need to import the crate in order to use it. Prefer to use module::function instead of importing a free function directly. This helps the developer track where they come from. The only exception I make is ...

12

Your code looks pretty decent. My two cents: Implement Default impl Default for Fifo { fn default() -> Fifo { Fifo { size: 0, read_idx: 0, write_idx: 0, buffer: [0; FIFO_CAPACITY], } } } Then you could simplify your new to: pub fn new() -> Fifo { Fifo::default() } Simplify ...

12

What about this: fn compare(a: &[u8], b: &[u8]) -> cmp::Ordering { for (ai, bi) in a.iter().zip(b.iter()) { match ai.cmp(&bi) { Ordering::Equal => continue, ord => return ord } } /* if every single element was equal, compare length */ a.len().cmp(&b.len()) } I've removed the ...

11

I took your code and got it to compile with my version of Rust (rustc 0.13.0-dev (29ad8539b 2014-12-24 16:21:23 +0000)). I ran with your parameters (I hope I understood them correctly) and got an average time of 207.8 ms. I made a few changes here and there, but the main thing was changing TreeMap to HashMap. TreeMap doesn't exist anymore, only BTreeMap. ...

11

The first thing I always do is running clippy. You will catch some things that are not neccessary, e.g. fn main() -> () can be reduced to fn main() let t = String::from(convert_type); is simply let t = convert_type The bad things are c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0) same for (f -...

11

I like this. Your code is clean and pretty readable. I recommend using rustfmt, if only because it will stop annoying people on the internet from recommending you use rustfmt. But the minor code formatting differences are not something to be overly concerned about, if you have a style and stick with it. I have two major suggestions: Don't populate the cache ...

10

With both scoring and merging Oops! I did indeed neglect to include merging. This is my mistake; I'm not a big fan of returning values via mutable parameters, so I think my brain shut off. Fortunately, while working on the merging logic, I made the scoring logic shorter. // Comment #1 fn compress_zeroes(line: [u8, ..4]) -> (u8, u8, u8, u8) { let mut ...

10

Firstly, you should use rsplit and next rather than split and last, as it starts at the more appropriate end: fn basename<'a>(path: &'a str, sep: char) -> Cow<'a, str> { let pieces = path.rsplit(sep); match pieces.next() { Some(p) => p.into(), None => path.into(), } } Secondly, you shouldn’t be using ...

10

There's not a lot of code here so there's not a lot to say. ^_^ Implementations like this are generally outside of the day-to-day knowledge of most programmers. You may wish to include a reference in the code to how the algorithm was derived and how it works. The chosen variable names are pretty useless. I have no idea what an or sm mean. Because I don't ...

10

As you have already been made aware, you should not be using &mut Vec<T> unless you plan on adding or removing items from the Vec. Using &mut [T] better expresses the contract of the function and is more flexible, allowing you to also sort arrays and anything else that can be expressed as a slice. where clauses go on a separate line. This ...

10

Forgive me, I am unable to review the rust code because I do not know rust, I am only reviewing the c++ code.. Use System Defined Exit Codes Returning -1 as an exit code from a c++ program is rather uncommon, the generally accepted values to return from a c++ program are zero for success and one for failure. What is even better is that if the cstdlib ...

9

Profile You can only improve what you can measure. So first of all let us run callgrind to check where we spent most of our time: $rustc -C opt-level=3 -g brainfuck.rs$ valgrind --tool=callgrind --dump-instr=yes --collect-jumps=yes --simulate-cache=yes ./brainfuck ahpla.bf \$ callgrind_annotate callgrind.out.* We will end up with something similar to the ...

8

The biggest thing I can say is listen to your tests. The very first thing I noticed as I was skimming is how repetitive they were. Even worse, the repeated parts drowned out the interesting aspects of the tests. Remember that your tests are your first chance to see how a potential end-user might use your code. Use them as an opportunity to reflect on your ...

8

You could use min_by_key to find the minimum's index and the method swap defined in slices: fn selection_sort(array: &mut [i32]) { let len = array.len(); for i in 0..len { let min = (i..len).min_by_key(|x| array[*x]) .unwrap(); array.swap(min, i); } }

8

The tests fail. That's not a good thing: ---- test_say_multi_line stdout ---- thread 'test_say_multi_line' panicked at 'assertion failed: (left == right) (left: " _______\n/ broke \\\n| n big |\n\\ bar /\n-------", right: " _______\n/ broke \\\n| n big |\n\\ bar /\n -------")', src/main.rs:153 ---- test_say_single_line stdout -...

8

Idiomatic Rust style is to place braces on same line. When the function definition gets longer than one line then the brace lives on the next line all on its own. Learn and love the entry API. Not only does the code end up clearer, it's faster too. Don't use magic numbers. What is 10 supposed to mean? Why not 9 or 11 or 42? The very least you can do is to ...

8

For overall issues, these jump out: s[i].is_alphabetic() && i < s.len() can panic, because you access the value before checking the length, it would have to be i < s.len() && s[i].is_alphabetic(). is_alphabetic considers lots of things alphabetic that you probably don't want. If you look at the docs the examples include assert!('京'....

8

Disclaimer: I'm also new to Rust, but I have a background in C, C++ and Haskell. Take everything I say with a grain of salt. All of that looks reasonable, except for the while loop and the ownership. And there's a bug. Bug on sorted vectors Did you try your code on sorted sets? #[test] fn it_works_on_sorted() { assert_eq!(merge_sort(vec![1, 2, 3, 4]),...

8

Disclaimer: I'm a Rust beginner with a background in C and C++. Now that I've lost my credibility, let's have a look at your code. Use rustfmt, clippy and rustc There are (at least) three helpful tools when one writes Rust code: rustfmt, clippy and the compiler rustc itself. Rustfmt provides a common ground The compiler doesn't yield any warnings, but ...

8

For deserialization, its a lost easier if you use serde. Then you can do something like this: use serde_derive::Deserialize; // the Deserialize derive is provided by serde, it causes the code // to be generated that is needed for deserialization #[derive(Default, Debug, Deserialize)] // this tells serde you want to use kebab-case, which is // with dashes ...

8

I take the idea to return an Ordering from the other answer: use std::cmp; pub fn compare(a: &[u8], b: &[u8]) -> cmp::Ordering { a.iter() .zip(b) .map(|(x, y)| x.cmp(y)) .find(|&ord| ord != cmp::Ordering::Equal) .unwrap_or(a.len().cmp(&b.len())) } You can use the powerful Rust iterators: zip allows ...

8

Welcome to Rust! Code Formatting There are some inconsistencies in your formatting — I have run cargo fmt to get rid of them. Naming There's no need to prefix everything with My or my_ — in Rust, your names won't as easily clash with existing names as might be the case in certain other languages. Error handling For applications, I suggest using the anyhow ...

7

Some style issues: Space before { Spaces around -> Space after , No space before : Space before else Indent else blocks 4 characters Make constructor functions part of the impl: impl Range { fn new(start: i32, end: i32) -> Range { Range { start: start, end: end, } } } Instead of creating a to_string ...

Only top voted, non community-wiki answers of a minimum length are eligible