Currently, I have a Struct that contains all the necessary configurations to set up a client for various object storage protocols. However, depending on the protocols, the necessary configuration differs, so all my fields are Option<>.
struct StorageConfig {
access_key: Option<String>,
secret_key: Option<String>,
endpoint: Option<String>,
region: Option<String>,
// ... other fields
}
I am currently considering implementing a validate
function that determines whether the required configuration for each object storage is inputted within the struct.
impl StorageConfig {
fn validate(&self, protocol: Protocol) -> Result<(), ConfigError> {
match protocol {
Protocol::A => {
if self.access_key.is_none() || self.secret_key.is_none() {
return Err(ConfigError::MissingField);
}
},
// ... other protocols
}
Ok(())
}
}
However, after the function it used, despite knowing that the required field is present, I would still need to be error handling on whether the field is Some() using ok_or_else() or some other methods to avoid panic.
if let Ok(_) = config.validate(Protocol::A) {
let client = ClientA::new(
config.access_key.as_ref().ok_or(ConfigError::MissingField)?,
config.secret_key.as_ref().ok_or(ConfigError::MissingField)?
);
// ...
}
This seems redundant, as I've already checked for the presence of these fields in validate
. Thus, is there a more convenient way to convert the Option<> fields into Some() during the validate
function?