英文:
How to set the default value of the following struct field?
问题
在这里,description 和 prompt 是可选的,因此它们的默认值是 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<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(),
            ..Default::default()
        }
    }
    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);
}
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>
> But I want `description`'s default value to be the value of `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()
        }
    }
}
?
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(&self) -> &str {
        self.description.as_deref().unwrap_or(&self.command)
    }
in which case you may want to impl Debug by hand.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论