如何访问与公共函数同名的struct字段?

And*_*oll 2 rust

我正在尝试访问clap::App我已实例化的特定版本.但是,该字段version与公共函数一样存在version()

以下是源代码的相关部分:

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
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我的代码:

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
Run Code Online (Sandbox Code Playgroud)

字段version和功能version()都存在App.怎么会这样?我怎样才能进入这个领域version

错误:

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?
Run Code Online (Sandbox Code Playgroud)

mca*_*ton 6

怎么会这样?

语言的定义方式使得字段和方法之间不存在冲突.

如何访问字段版本?

你不能:它是私有的,没有getter方法.


She*_*ter 5

您可以通过访问字段访问名称与函数相同的字段:

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());
}
Run Code Online (Sandbox Code Playgroud)

假设没有括号,您需要字段的值.

也可以看看: