oxigraph/rio

Error in NTriplesParser example

KonradHoeffner opened this issue · 2 comments

Using the example from https://docs.rs/rio_turtle/0.7.0/rio_turtle/struct.NTriplesParser.html and adding a main function:

use rio_api::model::NamedNode;
use rio_api::parser::TriplesParser;
use rio_turtle::{NTriplesParser, TurtleError};

fn main() {
    let file = b"<http://example.com/foo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .
<http://example.com/foo> <http://schema.org/name> \"Foo\" .
<http://example.com/bar> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .
<http://example.com/bar> <http://schema.org/name> \"Bar\" .";

    let rdf_type = NamedNode {
        iri: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
    };
    let schema_person = NamedNode {
        iri: "http://schema.org/Person",
    };
    let mut count = 0;
    NTriplesParser::new(file.as_ref()).parse_all(&mut |t| {
        if t.predicate == rdf_type && t.object == schema_person.into() {
            count += 1;
        }
        Ok(()) as Result<(), TurtleError>
    })?;
    assert_eq!(2, count);
}

This results in:

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
  --> src/main.rs:23:7
   |
5  | / fn main() {
6  | |     let file = b"<http://example.com/foo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .
7  | | <http://example.com/foo> <http://schema.org/name> \"Foo\" .
8  | | <http://example.com/bar> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .
...  |
23 | |     })?;
   | |       ^ cannot use the `?` operator in a function that returns `()`
24 | |     assert_eq!(2, count);
25 | | }
   | |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `FromResidual<Result<Infallible, TurtleError>>` is not implemented for `()`

I'm a Rust beginner so unfortunately I cannot give more details about it.

Tpt commented

Hi! Thank you for trying Rio and welcome to the Rust community.

The ? operator is a Rust shortcut to quickly abort the caller function is the called function returns an error. A quick and dirty way to avoid having to deal with this operator is to replace all occurences of ? with .unwrap(). unwrap aborts the current thread if an error is returned by the called function or returns the regula result value if not.

This chapter of the Rust book explains all these stuff around error handling.

Hi, thank you for welcoming me and for explaining it! The example works perfectly when replacing ? with unwrap and the chapter you linked has been very helpful.
I guess what tripped me up initially was that I thought I could just run the example as is, but it seems as if this style is the default in the Rust community.