keeping the same dependencies and logic, the rust code boils down to
use serde::Deserialize;
const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
#[derive(Deserialize)]
struct Story {
title: String,
}
fn main() {
let story_ids: Vec<u64> = reqwest::blocking::get(STORIES_URL).unwrap().json().unwrap();
let mut handles = Vec::new();
for id in &story_ids[..8] {
let oid = id.clone();
handles.push(std::thread::spawn(move || {
let story_url = format!("{}/{}.json", ITEM_URL_BASE, oid);
let story: Story = reqwest::blocking::get(&story_url).unwrap().json().unwrap();
println!("{}", story.title);
}));
}
for handle in handles {
handle.join().unwrap();
}
}
with Cargo.toml:
[package]
name = "hnfetch"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json", "blocking"] }
tokio = { version = "1", features = ["full"] }
if you want, you can can go full-on with iterators and maps:
use serde::Deserialize;
const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
#[derive(Deserialize)]
struct Story {
title: String,
}
fn main() {
let story_ids: Vec<u64> = reqwest::blocking::get(STORIES_URL).unwrap().json().unwrap();
story_ids[..8]
.into_iter()
.copied()
.map(|id| {
std::thread::spawn(move || {
let story_url = format!("{}/{}.json", ITEM_URL_BASE, id);
let story: Story = reqwest::blocking::get(&story_url).unwrap().json().unwrap();
println!("{}", story.title);
})
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|handle| handle.join().unwrap())
}
but neither case is as scary as the current code. I can offer a PR if needed
keeping the same dependencies and logic, the
rustcode boils down towith
Cargo.toml:if you want, you can can go full-on with iterators and maps:
but neither case is as scary as the current code. I can offer a PR if needed