pleroma.debian.social

pleroma.debian.social

Bikeshed color query

In Rust, I want to create a vector of length `size.x` and I want to initialize every member to a new object of type SmolBitmap. Is there a cleaner/more idiomatic/"better" way of doing it than

let mut visited:Vec<_> = (0..size.x).map(|_|SmolBitmap::new()).collect();

A real problem with Rust is it's very "golfable" so you can waste a lot of time trying to replace a single "good enough" line with a "best" solution

@mcc If SmolBitmap is `Clone` you can simplify it to `vec![SmolBitmap::new(); size.x]`

@mcc I looked for a while but couldn't find a better way

@mcc I would generally use with_capacity if I know the size up front.

@mcc for small N I might also build from a fixed array, possibly requires implementing Default on the type 🤷

@onelson the array size is not known at compile time. is that a problem?

@mcc yeah, array needs a const size

@mcc If you already have the vector you can do `my_vec.resize(size.x, SmolBitmap::new())`

@mcc One reason Python is so fast to write is you do not have this problem - it's all awful.

@mcc Haskell has that problem too
replies
0
announces
0
likes
0

@mcc

let mut visited: Vec<_> = std::iter::repeat_n(SmolBitmap::new(), size.x).collect();

Maybe? Iirc, this will clone SmolBitmap for every item.

@mcc omg yes!

@mcc
Here's another option that has not been mentioned yet:
std::iter::repeat_with(SmolBitmap::new).take(size.x).collect()

Edit: but it seems like SmolBitmap has deep clone() so the idiomatic vec![SmolBitmap::new(); size.x] is the best solution I guess

@mcc holy crap yes

@mcc I would do:

`Vec::from_iter(std::iter::repeat_with(SmolBitmap::new).take(size.x))`

@mcc Can't agree more, not a rust developer but can say the same thing for the whole javascript ecosystem, as opposed to something like go or c.

@mcc (someone else did already mention more or less this formulation but I am on a long term quest to get people to consider using T::from_iter more often, because no one seems to realize that I::collect<T> has a complement, the same way From has Into as a complement and which is clearer is situational)

@mcc let mut visited = Vec::with_capacity(size.x); visited.resize(size.x, SmolBitmap::new()) might be faster if SmolBitmap is Copy. resize_with doesn’t require Copy but then it’s probably same as collect()