Day 6: Wait for It


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ

  • Walnut356@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    11 months ago

    I’m no rust expert, but:

    you can use into_iter() instead of iter() to get owned data (if you’re not going to use the original container again). With into_iter() you dont have to deref the values every time which is nice.

    Also it’s small potatoes, but calling input.lines().collect() allocates a vector (that isnt ever used again) when lines() returns an iterator that you can use directly. You can instead pass lines.next().unwrap() into your functions directly.

    Strings have a method called split_whitespace() (also a split_ascii_whitespace()) that returns an iterator over tokens separated by any amount of whitespace. You can then call .collect() with a String turbofish (i’d type it out but lemmy’s markdown is killing me) on that iterator. Iirc that ends up being faster because replacing characters with an empty character requires you to shift all the following characters backward each time.

    Overall really clean code though. One of my favorite parts of using rust (and pain points of going back to other languages) is the crazy amount of helper functions for common operations on basic types.

    Edit: oh yeah, also strings have a .parse() method to converts it to a number e.g. data.parse() where the parse takes a turbo fish of the numeric type. As always, turbofishes arent required if rust already knows the type of the variable it’s being assigned to.

    • anonymouse@sh.itjust.works
      link
      fedilink
      arrow-up
      1
      ·
      11 months ago

      Thanks for making some time to check my code, really appreciated! the split_whitespace is super useful, for some reason I expected it to just split on single spaces, so I was messing with trim() stuff the whole time :D. Could immediately apply this feedback to the Challenge of today! I’ve now created a general function I can use for these situations every time:

          input.split_whitespace()
              .map(|m| m.parse().expect("can't parse string to int"))
              .collect()
      }
      

      Thanks again!