Dear All,
This is far fom pretty, even for my first bit of rustling. My little snippet reads some lines from a file and creates a collection of structs representing each record.
I know the logic is not pretty, but my approach was chosen to help me explore certain aspects of rust, not to create an efficient parser
Please can you review the rust aspects of this? What could I improve and why?
In particular, I really don't like the nest of if/for/if/if starting with if let Ok(lines) ... somethng really feels wrong there.
use regex::Regex;
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() {
let path = Path::new("./Data/cameras-defb.csv");
let display = path.display();
println!("Reding file: {}", display);
let mut v: Vec<Camera> = Vec::new();
if let Ok(lines) = read_lines(path) {
for line in lines {
if let Ok(l) = line {
let fields: Vec<&str> = l.split(';').collect();
if fields.len() == 3 && fields.get(0).unwrap().trim() != "Camera".to_string() {
let cam: Camera = Camera::from_vector(fields);
cam.dump();
v.push(cam);
}
}
}
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
struct Camera {
id: u16,
name: String,
lat: f32,
lng: f32,
}
impl Camera {
fn from_vector(fields: Vec<&str>) -> Camera {
let re = Regex::new("(\\d{3})").unwrap();
let first_field = fields.get(0).unwrap().to_string();
let newid: u16 = match re.find(&first_field) {
Some(x) => first_field[x.start()..x.end()].parse().unwrap(),
_ => 0,
};
Camera::from_fields(
newid,
fields.get(0).unwrap().to_string(),
fields.get(1).unwrap().to_string().trim().parse().unwrap(),
fields.get(2).unwrap().to_string().trim().parse().unwrap(),
)
}
}
impl Camera {
fn from_fields(id: u16, name: String, lat: f32, lng: f32) -> Camera {
Camera {
id: id,
name: name,
lat: lat,
lng: lng,
}
}
}
impl Camera {
fn dump(&self) -> () {
println!(
"{} | {} | {} | {}",
self.id.to_string(),
self.name,
self.lat.to_string(),
self.lng.to_string()
);
}
}