I'm trying to learn Rust. To begin with, I set myself the exercise of
choosing a random picture from a bunch of .zip files. (The next step
is to incorporate this into a simple web framework to generate a slideshow
as I'm interested in learning Rust web frameworks, having explored
Python, PHP and Node.)
I can do this easily in Python, and the Python probably does a better job of what I'm trying to do in Rust.
import glob
import random
import zipfile
# Exercise 1: pick a .zip at random
zips = glob("*.zip")
z = random.choice(zips)
print(z)
# Exercise 2: pick a .zip at random, and pick a file at random
zips = glob("*.zip")
z = random.choice(zips)
with zipfile.ZipFile(z) as zf:
fn = random.choice(zf.namelist())
print(z,fn)
# Exercise 3: make a single list of pairs (zip_file_name,file_name)
# Then choose one at random
files = []
zips = glob("*.zip")
for zfn in zips:
with zipfile.ZipFile(z) as zf:
for fn in zf.namelist():
files.append((zfn,fn))
print(random.choice(files))
My first attempt got lost in a pile of .unwrap()
s and similar, and I was at a loss how to turn a glob into something I can choose randomly from. (For example, where in Python we can use list(x) for any sequence x to convert it to a list. In rust I've come across .collect()
, but then I need to know the resulting type.)
For example
use glob::glob; fn main() {
let zips_glob = glob::glob("*.zip").expect("Failed to read glob pattern");
let zips = zips_glob.collect();
println!("{:?}",zips); }
yields
error[E0282]: type annotations needed
--> src/main.rs:12:8
|
12 | let zips = zips_glob.collect();
| ^^^^
|
help: consider giving `zips` an explicit type
|
12 | let zips: _ = zips_glob.collect();
so how to I work out the right type annotation? And do I need to do some map
with unwrap
of something so that I end up with a bunch of paths I can choose randomly from?