lopdf icon indicating copy to clipboard operation
lopdf copied to clipboard

should return Result or Option to accept ? In Modify PDF document sample

Open josejachuf opened this issue 3 years ago • 2 comments

Hi. First approach to Rust. I'm just starting with Rust and I'm interested in using lopdf.

rustc 1.54.0 (a178d0322 2021-07-26) cargo 1.54.0 (5ae8d74b3 2021-06-22)

I'm testing the sample code but I get an error

msin.rs

use lopdf::Document;


fn main() {
    let mut doc = Document::load("example.pdf")?;
    doc.version = "1.4".to_string();
    doc.replace_text(1, "Hello World!", "Modified text!");
    doc.save("modified.pdf")?;
}

doc.save("modified.pdf")?; | | ^ cannot use the ? operator in a function that returns () 8 | | } | |_- this function should return Result or Option to accept ?

José

josejachuf avatar Aug 19 '21 18:08 josejachuf

Hello, welcome to Rust.

You're getting that error because the main function doesn't return anything hence why it complains that it should only return (). If you want your program to crash for Result errors, use the unwrap method instead.

Here are some helpful references on how to handle Result: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html https://doc.rust-lang.org/rust-by-example/error/result.html

donmai-me avatar Aug 21 '21 01:08 donmai-me

Hello, thanks for the answer. I did the following modification (without knowing what it was doing very well). and works fine.

use lopdf::{Document};

fn main() {

    let doc = Document::load("example-2.pdf");
    let mut doc = match doc {
        Ok(f) => f,
        Err(error) => panic!("Problem opening the pdf: {:?}", error),
    };

    doc.version = "1.4".to_string();
    doc.replace_text(1, "Hello World!", "Modified text!").expect("Error");
    doc.save("modified.pdf").unwrap();
}

What can be improved in this code?

Jose

josejachuf avatar Aug 22 '21 00:08 josejachuf