Panic in CSV parsing

I have tried to simplify the code to the portion which is failing. I'm trying to deserialize a csv file but it keeps falling. The input csv file contains only one line:


use std::fs::File;
use std::io::{BufReader};
use std::error::Error;
extern crate serde;
use serde::{ Deserialize};

#[derive(Deserialize, Debug,)]
struct Record {
    #[serde(deserialize_with = "default_if_empty")]
    search_sentence: String,
    #[serde(deserialize_with = "default_if_empty")]
    search_clue: String,

fn default_if_empty<'de, D, T>(de: D) -> Result<T, D::Error>
where D: serde::Deserializer<'de>, T: serde::Deserialize<'de> + Default,
    use serde::Deserialize;
    Option::<T>::deserialize(de).map(|x| x.unwrap_or_else(|| T::default()))

fn load_input (myinfile: &str) -> Result<(), Box<Error>> {
    let mut rdr = csv::ReaderBuilder::new()

    for result in rdr.deserialize() {
        let record: Record = result.unwrap();
        println!("{:?}", record);

fn main() {
    let myinfile = "input.txt";
    let mut input_vector = load_input(myinfile);

It fails with the error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error(Deserialize { pos: Some(Position { byte: 0, line: 1, record: 0 }), err: DeserializeError { field: None, kind: Message("invalid length 1, expected struct Record with 2 elements") } })', src\libcore\

You set your delimiter to semicolon instead of comma

Also you can rewrite

x.unwrap_or_else(|| T::default())



OMG! So simple! I copied that code "boiler plate" and missed that.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.