I ran the same prompt through ChatGPT (3.5), and provided the go code to make it give use the equivalent factoring and the rust code is still more readable than go (
use csv::ReaderBuilder;
use reqwest::blocking::Client;
use serde::Deserialize;
use std::error::Error;
#[derive(Debug, Deserialize)]
struct Data {
#[serde(rename = "key")]
value: String,
}
fn fetch_data(url: &str) -> Result<Vec<Data>, Box<dyn Error>> {
let response = Client::new().get(url).send()?;
let data: Vec<Data> = response.json()?;
Ok(data)
}
fn process_csv(csv_file: &str) -> Result<(), Box<dyn Error>> {
let file = std::fs::File::open(csv_file)?;
let mut rdr = ReaderBuilder::new().from_reader(file);
// Skip the header row
rdr.headers().unwrap();
for result in rdr.records() {
let record = result?;
let url = &record[0];
match fetch_data(url) {
Ok(data) => {
println!("Data from {}: ", url);
for item in data {
println!("{}: {}", "key", item.value);
}
println!();
}
Err(e) => eprintln!("Failed to fetch data from {}: {}", url, e),
}
}
Ok(())
}
fn main() {
let csv_file = "your_csv_file.csv";
if let Err(e) = process_csv(csv_file) {
eprintln!("Error processing CSV: {}", e);
}
}
My prompt was:
Please write some rust code for me that goes through every row of a CSV file, performs a get request for the value in the first column, and parses the responses as a JSON map of strings to strings.
The code should be the rust equivalent of the following go code:...
I also added at the end "Use reqwest for the http calls" as chatgpt spat out some code using ureq which was worse than the reqwest version it used without telling it to make the equivalent of the go code.
The main difference I see in the two is that as a go developer the language forces you to become intentionally code-blind to the error handling ceremony. `if err != nil` is effectively punctuation, but it's treated the same as your actual program by representing it as tokens.
Go treats the tuple(result, err) as a good-enough error handling approach. Rust says here's something equivalent but better.