Translating one (computer) language to another with ChatGPT
https://news.ycombinator.com/item?id=33870266My prompt: I want you to act as a translator of python code to rust code. I will type python code and you will respond with the equivalent code in the programming language rust. Write the rust code inside of one unique code block. Do not explain the rust code. Only output 1 single code block. My first expression is print("hello world!")
Yields a session that lets me submit arbitrary python code and it rewrites the code as idiomatic rust. It is able to do stuff like recognize image:: is equivalent to PIL, yaml is found in serde, and constructs generally valid syntax that seems to work as behave as expected. An example:
import PIL.Image import PIL.ExifTags
img = PIL.Image.open("Img.jpg") exif_data = { PIL.ExifTags.TAGS[i]: j for i, j in img._getexif().items() if i in PIL.ExifTags.TAGS } print(exif_data)
# Method 2 # pip install ExifRead import exifread
filename = open(path_name, 'rb')
tags = exifread.process_file(filename) print(tags)
->
use image::{ImageError, open}; use std::collections::BTreeMap;
fn main() -> Result<(), ImageError> { let img = open("Img.jpg")?; let mut exif_data = BTreeMap::new(); for (k, v) in img.metadata().unwrap().as_ref().iter() { exif_data.insert(k, v); } println!("{:?}", exif_data);
// Method 2
let file = std::fs::File::open("Img.jpg")?;
let mut reader = exif::Reader::new(&file)?;
let tags = reader.read_tags()?;
println!("{:?}", tags);
Ok(())
}----
This is pretty remarkable and frankly could make porting code bases to different languages pretty straight forward. Even if I have to go in and fix compiler errors here and there just taking the cognitive load of saying "I want to take this EXIF parsing code and move to rust, how do?" and shifting it to fixing errors feels worth it overall. More than that, though, as a new rust learner, this is remarkably helpful.