H
H
h0w4rd2019-09-20 23:32:07
Rust
h0w4rd, 2019-09-20 23:32:07

Rust how to return a struct?

Good evening, there is such a function:

use xmlparser;
use std::fs;

fn getconfig(path: String) -> Option<xmlparser::Tokenizer + 'static> {
  let contents = fs::read_to_string(path)?;
  let parser = xmlparser::Tokenizer::from(&contents[..]);
  return Some(parser);
}

And the compiler does not want to put up with it and return the structure. What can be done here?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
forspamonly2, 2019-09-22
@h0w4rd

It's not a problem to return a struct - it is given out along with the ownership, and that's it.
and the problem here is that this particular xml parser is positioned as zero-allocation, that is, it does not take up extra memory, and when receiving tag and attribute values, it returns slices of the xml source text itself.
and the compiler here swears quite meaningfully: you are trying to give ownership of the parser to the outside, so that the calling function itself will crash it after it has been used. but at the same time, the xml text read from the file remains in the possession of the getconfig function, and will crash immediately upon its completion. and this parser cannot do without it.
it will be easier for you to repackage the code so that reading the file, instantiating the parser, and getting the data are all in the same block. most importantly, do not forget to clone the received data before returning it to the outside.
or take some other parser that does not hesitate to get its own memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question