如何设置以下结构字段的默认值?

huangapple go评论56阅读模式
英文:

How to set the default value of the following struct field?

问题

在这里,descriptionprompt 是可选的,因此它们的默认值是 None

#[derive(Debug, Default)]
pub struct Keymap {
    pub key: char,
    pub command: String,
    pub description: Option<String>,
    pub prompt: Option<String>,
}

impl Keymap {
    pub fn new<S: AsRef<str>>(key: char, command: S) -> Self {
        Self {
            key,
            command: command.as_ref().to_owned(),
            description: None, // 默认情况下 description 是 None
            prompt: None, // 默认情况下 prompt 是 None
        }
    }

    pub fn with_prompt<S: AsRef<str>>(mut self, prompt: S) -> Self {
        self.prompt = Some(prompt.as_ref().to_owned());
        self
    }

    pub fn with_description<S: AsRef<str>>(mut self, description: S) -> Self {
        self.description = Some(description.as_ref().to_owned());
        self
    }
}

fn main() {
    let keymap = Keymap::new('a', "echo Hello, World!")
        .with_prompt("Enter your name:")
        .with_description("Prints 'Hello, World!'");

    println!("{:?}", keymap);
}

但我想要 description 的回退值是 command 的值。如果提供了 description,那么应该使用该值。

如何实现这一点?

英文:

Here, description and prompt are optional, so their default value is None.

#[derive(Debug, Default)]
pub struct Keymap {
    pub key: char,
    pub command: String,
    pub description: Option&lt;String&gt;,
    pub prompt: Option&lt;String&gt;,
}

impl Keymap {
    pub fn new&lt;S: AsRef&lt;str&gt;&gt;(key: char, command: S) -&gt; Self {
        Self {
            key,
            command: command.as_ref().to_owned(),
            ..Default::default()
        }
    }

    pub fn with_prompt&lt;S: AsRef&lt;str&gt;&gt;(mut self, prompt: S) -&gt; Self {
        self.prompt = Some(prompt.as_ref().to_owned());
        self
    }

    pub fn with_description&lt;S: AsRef&lt;str&gt;&gt;(mut self, description: S) -&gt; Self {
        self.description = Some(description.as_ref().to_owned());
        self
    }
}

fn main() {
    let keymap = Keymap::new(&#39;a&#39;, &quot;echo Hello, World!&quot;)
        .with_prompt(&quot;Enter your name:&quot;)
        .with_description(&quot;Prints &#39;Hello, World!&#39;&quot;);

    println!(&quot;{:?}&quot;, keymap);
}

Rust Playground

But I want description's fallback value to be the value of command. If a description is provided, then that value should be used.

How to accomplish that?

答案1

得分: 2

> 但我希望 `description` 的默认值是 `command` 的值。

```rust
impl Keymap {
    pub fn new<S: AsRef<str>>(key: char, command: S) -> Self {
        let command = command.as_ref().to_string();
        Self {
            key,
            description: Some(command.clone()),
            command,
            ..Default::default()
        }
    }
}

不确定为什么 description 仍然是一个 Option

或者,就在消费者方面回退。

如果你在问是否有办法使 description 在没有显式设置的情况下自动成为 command 的副本,那么答案是否定的。不过,你可以通过将 description 保持私有并通过方法访问来模拟这种情况,例如:

pub fn description(&self) -> &str {
    self.description.as_deref().unwrap_or(&self.command)
}

在这种情况下,你可能需要手动实现 Debug


<details>
<summary>英文:</summary>

&gt; But I want `description`&#39;s default value to be the value of `command`.

```rust
impl Keymap {
    pub fn new&lt;S: AsRef&lt;str&gt;&gt;(key: char, command: S) -&gt; Self {
        let command = command.as_ref().to_string();
        Self {
            key,
            description: Some(command.clone()),
            command,
            ..Default::default()
        }
    }
}

?

Not sure why description would still be an Option tho.

Alternatively, just fallback on the consumer side.

If you're asking if there's a way to make description magically be a copy of command unless it's explicitly set, then no. Though you could emulate that by keeping description private and accessing it via a method e.g.

    pub fn description(&amp;self) -&gt; &amp;str {
        self.description.as_deref().unwrap_or(&amp;self.command)
    }

in which case you may want to impl Debug by hand.

huangapple
  • 本文由 发表于 2023年7月4日 23:02:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定