Returning object containing references in Rust -


i have following 2 types:

struct {     x: int }  struct b<'a> {     y: &'a } 

i create function creates object of type , object of type b containing reference object of type a, , returns object of type b:

fn bar<'a>() -> b<'a> {     let y = { x: 3 };     b { y: &y } } 

however following compiler error:

main.rs:11:13: 11:14 error: `y` not live long enough main.rs:11     b { y: &y }                        ^ main.rs:9:23: 12:2 note: reference must valid lifetime 'a defined on block @ 9:22... main.rs:9 fn bar<'a>() -> b<'a> { main.rs:10     let y = { x: 3 }; main.rs:11     b { y: &y } main.rs:12 } main.rs:9:23: 12:2 note: ...but borrowed value valid block @ 9:22 main.rs:9 fn bar<'a>() -> b<'a> { main.rs:10     let y = { x: 3 }; main.rs:11     b { y: &y } main.rs:12 } error: aborting due previous error 

this error seems justified, can't find way around issue. there way specify lifetime of y should @ least 'a, without changing definition of a or b?

there no way specify y lifetime should @ least 'a because impossible: y local variable , cannot live longer stack frame created in.

in general, if find need such thing, in fact want b own a:

struct b { y: } 

in case code becomes trivial:

fn bar() -> b {     let y = { x: 3 }     b { y: y } } 

you can point. signature of bar() want:

fn bar<'b>() -> b<'b> { ... } 

'b lifetime parameter, is, can chosen arbitrarily caller of function. nothing prevents caller substitute, example, 'static 'b:

let x: b<'static> = bar(); 

however, possible if bar() always return b<'static>, not want, seems. in fact, above signature equivalent one:

fn bar() -> b<'static> { ... } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -