0

I have a file containing prime numbers that I'm unpacking into a u32 vector. I'm curious if I can do this in one step. If I unpack contents into a str vector, then an u32 vector, everything's dandy.

If I try to move everything into a u32 vector as I try to do in v_int2, I get the error that

|&x| doesn't have a known size at compile time.

My current understanding is that &str has a known size at compile time, since &str are written into the binary. Skipping this step means I'm parsing from String to u32, and I need to inform the compiler about something having to do with the size of my elements. I'm not aware of a way around this, though I'm new in Rust town.

let mut file = File::open("first10kprimes.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;

let v_str = contents.split_whitespace().collect::<Vec<&str>>(); // I just discovered I could do that typing after collect, was a lil jazzed
let v_int: Vec<u32> = v_str.iter().map(|&x| x.parse::<u32>().unwrap()).collect();

let v_int2: Vec<u32> = contents
    .split_whitespace()
    .map(|&x| x.parse().unwrap())
    .collect();
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
cryptograthor
  • 455
  • 1
  • 7
  • 19
  • 1
    *since `&str` are written into the binary* — this is incorrect. Only string **literals** are in the binary. – Shepmaster Mar 03 '20 at 15:22
  • 1
    [The duplicate applied to your case](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=23df7821f1573d01247cd44fb2ae0119). – Shepmaster Mar 03 '20 at 15:26
  • 1
    https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=6a29665670ccd69d27e7e657f3d5d9e3 – Boiethios Mar 03 '20 at 15:27
  • 1
    You already have most of the solution. You just need to remove the `&` in your closure: `.map(|x| x.parse().unwrap())` – Jmb Mar 03 '20 at 15:28
  • The code posted in this question is inefficient as it builds up a needless intermediate vector (`Vec<&str>`). It's better to chain the iterators. – Shepmaster Mar 03 '20 at 15:34
  • @Shepmaster: damn, the Rust god of stack overflow is fast. I think I misunderstand; &str == string literal? I thought this to be true. I'm aware the code is inefficient, and was asking about how to make it better. – cryptograthor Mar 03 '20 at 15:45
  • @Jmb, thanks, that does it! – cryptograthor Mar 03 '20 at 15:46
  • 2
    All string literals are `&str`; not all `&str` are string literals. [What does the word “literal” mean?](https://stackoverflow.com/q/485119/155423) – Shepmaster Mar 03 '20 at 15:47

0 Answers0