voglio scrivere questa struttura:Come scrivere la struttura corretta della durata in Rust?
struct A {
b: B,
c: C,
}
struct B {
c: &C,
}
struct C;
Il B.c
dovrebbero essere presi in prestito da A.c
.
A ->
b: B ->
c: &C -- borrow from --+
|
c: C <------------------+
Questo è quello che ho provato:
struct C;
struct B<'b> {
c: &'b C,
}
struct A<'a> {
b: B<'a>,
c: C
}
impl<'a> A<'a> {
fn new<'a>() -> A<'a> {
let c = C;
A {c: c, b: B{c: &c}}
}
}
ma non riesce:
test.rs:17:21: 17:22 error: `c` does not live long enough
test.rs:17 A {b: B{c: &c}, c: &c}
^
test.rs:15:27: 18:6 note: reference must be valid for the lifetime 'a as defined on the block at 15:26...
test.rs:15 fn new<'a>() -> A<'a> {
test.rs:16 let c = C;
test.rs:17 A {b: B{c: &c}, c: &c}
test.rs:18 }
test.rs:15:27: 18:6 note: ...but borrowed value is only valid for the block at 15:26
test.rs:15 fn new<'a>() -> A<'a> {
test.rs:16 let c = C;
test.rs:17 A {b: B{c: &c}, c: &c}
test.rs:18 }
test.rs:17:29: 17:30 error: `c` does not live long enough
test.rs:17 A {b: B{c: &c}, c: &c}
^
test.rs:15:27: 18:6 note: reference must be valid for the lifetime 'a as defined on the block at 15:26...
test.rs:15 fn new<'a>() -> A<'a> {
test.rs:16 let c = C;
test.rs:17 A {b: B{c: &c}, c: &c}
test.rs:18 }
test.rs:15:27: 18:6 note: ...but borrowed value is only valid for the block at 15:26
test.rs:15 fn new<'a>() -> A<'a> {
test.rs:16 let c = C;
test.rs:17 A {b: B{c: &c}, c: &c}
test.rs:18 }
error: aborting due to 2 previous errors
Ho letto la documentazione Ruggine sulla proprietà, ma io ancora non so come aggiustalo.
Se ci sono articoli utili, fatemi sapere nei commenti.
"è l'errore" non è una spiegazione sufficiente del problema. Se il compilatore restituisce un errore, inseriscilo e comunicaci da quale linea proviene. –
@DavidGrayson grazie, ho pubblicato. –
@geotheory Scusa, il mio inglese è pessimo, ora ho cambiato il titolo. –