How to use default_value with customized data struct? #5783
-
Hello, use clap::Parser;
#[derive(Clone)]
pub struct Color {
r: u8,
g: u8,
b: u8,
a: u8,
}
impl Color {
pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
}
impl Into<[u8; 4]> for &Color {
/// Translate this to byte reprensation,
/// in ARGB8888 format.
fn into(self) -> [u8; 4] {
[self.a, self.r, self.g, self.b]
}
}
impl From<Color> for clap::builder::OsStr {
fn from(value: Color) -> Self {
format!("#{:x}{:x}{:x}{:x}", value.r, value.g, value.b, value.a).into()
}
}
impl core::str::FromStr for Color {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Some conditions
Ok(Color::new(0,0,0,0))
}
}
#[derive(Parser)]
pub struct Config {
#[arg(value_parser=|v:&str| v.parse::<Color>(), default_value=Color::new(255, 0, 0, 255))]
background_color: Color,
}
impl Config {
pub fn background_color(&self) -> &Color {
&self.background_color
}
}
fn main() {
println!("Hello, world!");
} (some details are hidden for not distinguishing)
I'm temporary using |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
impl From<Color> for clap::builder::OsStr {
fn from(value: Color) -> Self {
format!("#{:x}{:x}{:x}{:x}", value.r, value.g, value.b, value.a).into()
}
} This requires The compiler would report this if you |
Beta Was this translation helpful? Give feedback.
-
btw you probably want |
Beta Was this translation helpful? Give feedback.
-
yes, you'd probably right, thanks.
…________________________________
From: Ed Page ***@***.***>
Sent: Monday, October 21, 2024 9:53:56 AM
To: clap-rs/clap ***@***.***>
Cc: GNUqb114514 ***@***.***>; Author ***@***.***>
Subject: Re: [clap-rs/clap] How to use default_value with customized data struct? (Discussion #5783)
btw you probably want default_value_t rather than default_value. default_value_t is meant for default values in your native type while default_value is for OsStr defaults, representing the form used on the command line.
―
Reply to this email directly, view it on GitHub<#5783 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/A2KCXSGZDRXZFYU47GBD353Z4RNDJAVCNFSM6AAAAABQIMZFLSVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTAOJZHE4DAMI>.
You are receiving this because you authored the thread.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
btw you probably want
default_value_t
rather thandefault_value
.default_value_t
is meant for default values in your native type whiledefault_value
is forOsStr
defaults, representing the form used on the command line.