How to set deep value with `?`

neither of the set functions here work… any tips?

struct Foo {
    a: Option<Bar>

struct Bar {
    b: Baz

struct Baz {
    c: Option<u32>

fn set_deep_value(example:Foo) -> Option<Foo> {
    example.a?.b.c = Some(42);

fn set_deep_value_ref(example:&mut Foo) -> Option<()> {
    example.a?.b.c = Some(42);

Fwiw this get also doesn’t compile:

fn get_deep_value_ref(example:&Foo) -> Option<u32> {


EDIT: the ref example was kinda weird before - made it slightly saner

Can you try this ?

fn set_deep_value(example: Foo) -> Option<Foo> {
    Some(Foo{a: Some(Bar{b: Baz{c: Some(42)}, .. example.a? })})

You are close. The problem is that the ? takes the value out of the Option Foo::a and destroyes the Foo in the process because Bar is not copy.
There are two helpful methods Option::as_ref and Option::as_mut you can use here.
If you do you will see that the mutability is off. You are changing example but did not declare it mutable.
Putting it all together you get:


Sorry about changing the example - and I still didn’t catch that I needed the mut for the non-borrow example too :wink:

Thanks - will look into as_ref / as_mut!