3
\$\begingroup\$

I want to get version from Cargo.toml and use the value inside my app. Here is a function I wrote:

use std::fs;

pub fn get_version() -> &'static str {
    let text = fs::read_to_string("Cargo.toml").unwrap();
    for line in text.split("\n") {
        if line.starts_with("version") {
            let start = line.find('"').unwrap() + 1;
            let end = line.rfind('"').unwrap();
            let version = &line[start..end];
            return Box::leak(version.to_string().into_boxed_str());
        }
    }

    panic!("failed parsing version from Cagro.toml");
}

Writting the function, I had some questions. So I'd like to get help from others.

  • How can I replace for and if nested blocks with iterator methods?
  • To return value as static lifetime, I used Box::leak(version.to_string().into_boxed_str()) which is too complicated (&str -> String -> Box<str> just for avoiding compile errors). How can I return &'static str or &'a str simply without getting cannot return value referencing local variable ... error in this case?
  • Can I make the code simpler? (ex: parsing the version value)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Do you know about macro env!? \$\endgroup\$
    – aSpex
    Apr 10, 2019 at 14:57
  • \$\begingroup\$ @aSpex Thanks for the information. I can easily get Cargo version via env!. Apart from it, I'd like to get my code reviewed. \$\endgroup\$
    – philipjkim
    Apr 11, 2019 at 1:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.