【问题标题】:How do I access a struct field which has the same name as a public function?如何访问与公共函数同名的结构字段?
【发布时间】:2018-10-02 18:45:29
【问题描述】:

我正在尝试访问我已实例化的特定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
    }
    // ...
}

还有我的代码:

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

字段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?

【问题讨论】:

    标签: rust


    【解决方案1】:

    这怎么可能?

    语言的定义方式是字段和方法之间没有冲突。

    如何访问现场版本?

    你不能:它是私有的并且没有 getter 方法。

    【讨论】:

      【解决方案2】:

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

      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());
      }
      

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

      另见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 2015-04-24
        • 2017-11-10
        • 2014-07-13
        • 2017-04-30
        • 2019-06-24
        • 2013-09-11
        相关资源
        最近更新 更多