New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Question] Why FluentBundle::format_pattern takes Option<'bundle FluentArgs> #260
Comments
Btw, I think I solved my problem by reordering some lifetimes or just writing better code. pub struct Locale {
langs: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
current_lang: LanguageIdentifier,
fallback: LanguageIdentifier,
}
impl Locale {
fn bundle(&self) -> &FluentBundle<FluentResource> {
self.langs
.get(&self.current_lang)
.expect("failed to get bundle for current locale")
}
fn fallback(&self) -> &FluentBundle<FluentResource> {
self.langs
.get(&self.fallback)
.expect("failed to get bundle for fallback locale")
}
fn get_entry(&self, key: &str) -> Option<Entry> {
let first_bundle = self.bundle();
let first_msg = first_bundle.get_message(key);
if let Some(msg) = first_msg {
Some(Entry {
bundle: first_bundle,
msg,
})
} else {
let fallback = self.fallback();
Some(Entry {
bundle: fallback,
msg: fallback.get_message(key)?,
})
}
}
// Generic way to get message with or without arguments
pub fn try_msg_cow<'a>(
&'a self,
key: &str,
args: Option<&'a FluentArgs>,
) -> Option<Cow<str>> {
let Entry { bundle, msg } = self.get_entry(key)?;
let mut errs = Vec::new();
let msg = bundle.format_pattern(msg.value()?, args, &mut errs);
for err in errs {
eprintln!("err: {err}")
}
Some(msg)
}
} And it doesn't even require calling |
And I think I understand now why this is the case (because we may reference args), so closing this. |
format_pattern has the following signature:
And if I read lifetimes right, it means that args must have the same lifetime as a result. And it's impossible to create args at runtime because their lifetime will be obviously less than the bundle.
I have this code for i18n in my app.
And because the result of try_msg_ctx borrows lifetime from args, I can't use Cow here and am forced to use String. This means I need to duplicate the code to get message with arguments and without arguments because in the latter case I don't need to create a new string, I can just get it from the bundle, but in the former case, I obviously need to create an owned string. And it seems that I should be ok with just using Cow<'bundle, string>, but because format_pattern links args and result, it doesn't compile (because args will always have a lesser lifetime).
So, my understanding is wrong or things actually can be improved so that args can have their own lifetime?
The text was updated successfully, but these errors were encountered: