Do not put question mark initialization expressions behind a reference

This commit is contained in:
Guillaume Gomez 2025-04-12 21:03:17 +02:00 committed by René Kijewski
parent 7727d4032b
commit ddfdd20855
2 changed files with 28 additions and 1 deletions

View File

@ -967,7 +967,8 @@ impl<'a> Generator<'a, '_> {
self.visit_target(buf, true, true, &l.var);
// If it's not taking the ownership of a local variable or copyable, then we need to add
// a reference.
let (before, after) = if !matches!(**val, Expr::Var(name) if self.locals.get(name).is_some())
let (before, after) = if !matches!(**val, Expr::Try(..))
&& !matches!(**val, Expr::Var(name) if self.locals.get(name).is_some())
&& !is_copyable(val)
{
("&(", ")")

View File

@ -196,3 +196,29 @@ fn test_moving_local_vars() {
};
assert_eq!(x.render().unwrap(), "ABCDEFG");
}
// Ensure that if a variable initialization expression ends with a `?`, we don't put it behind
// a reference.
#[test]
fn test_variable_from_question_mark_init_expr() {
#[derive(Template)]
#[template(
source = r#"
{%- let v2 = v.as_str().ok_or("error")? %}
{%- if v2 == "foo" %}1{% endif -%}
"#,
ext = "txt"
)]
struct X {
v: B,
}
struct B;
impl B {
fn as_str(&self) -> Option<&'static str> {
Some("foo")
}
}
assert_eq!(X { v: B }.render().unwrap(), "1");
}