7

I'm trying to access the version of a particular clap::App I have instantiated. However, the field version exists as does the public function version()

Here is the relevant bits of source code:

pub struct App<'a, 'v, 'ab, 'u, 'h, 'ar> {
    // ...
    version: Option<&'v str>,
    // ...
}

impl<'a, 'v, 'ab, 'u, 'h, 'ar> App<'a, 'v, 'ab, 'u, 'h, 'ar>{
    // ...
    pub fn version(mut self, v: &'v str) -> Self {
        self.version = Some(v);
        self
    }
    // ...
}

And my code:

pub fn build_cli() -> App<'static, 'static> {
    App::new("my-pi")
        .version("0.1.0")
// ...

let app = build_cli();
assert_eq!(app.version, "0.1.0"); // <-- Error here

The field version and function version() both exist on App. How can this be? And how can I access the field version?

The error:

error[E0615]: attempted to take value of method `version` on type `clap::App<'_, '_>`
  --> src/cli.rs:27:21
   |
27 |         assert_eq!(app.version, "0.1.0");
   |                        ^^^^^^^
   |
   = help: maybe a `()` to call it is missing?
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Andrew Graham-Yooll
  • 2,148
  • 4
  • 24
  • 49

2 Answers2

12

You access a field that is named the same as a function by accessing the field:

struct Example {
    foo: i32,
}

impl Example {
    fn foo(&self) -> i32 {
        self.foo + 100
    }
}

fn main() {
    let ex = Example { foo: 42 };

    println!("{}", ex.foo);
    println!("{}", ex.foo());
}

It is assumed that, without the parenthesis, you want the field's value.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
11

How can this be?

The language is defined in such a way that there is no conflict between fields and methods.

How can I access the field version?

You can't: it is private and does not have a getter method.

mcarton
  • 27,633
  • 5
  • 85
  • 95