How do I update a field in a csv::ByteRecord?

前端 未结 1 1694
醉话见心
醉话见心 2021-01-15 18:24

I am trying to parse a CSV file and if a certain field matches, update a certain field with a different value, but I\'m not sure on how to do this.

My code:

<
1条回答
  •  囚心锁ツ
    2021-01-15 19:08

    You don't. A ByteRecord (and a StringRecord by extension) store all of the field's data in a single tightly-packed Vec. You cannot easily access this Vec to modify it and the currently exposed mutation methods are too coarse to be useful in this case. You could remove fields from the end of the record or clear the entire thing, but not replace one field.

    Instead, you can create a brand new ByteRecord when needed and output that:

    for result in rdr.byte_records() {
        let input_record = result?;
    
        let output_record = if &input_record[0] == b"05V" && &input_record[4] == b"4" {
            input_record
                .into_iter()
                .enumerate()
                .map(|(i, v)| if i == 4 { b"2" } else { v })
                .collect()
        } else {
            input_record
        };
        wtr.write_byte_record(&output_record);
    }
    

    0 讨论(0)
提交回复
热议问题