I'm trying to mutate a struct using a function filling some optional fields. After I filled the fields I want to use the struct to do whatever, but I always get the following error.
error[E0502]: cannot borrow `txn` as immutable because it is also borrowed as mutable
--> src/asynch/transaction/mod.rs:263:26
|
259 | let txn1 = &mut txn;
| -------- mutable borrow occurs here
...
263 | println!("{:?}", txn);
| ^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
Here is the actual test code:
#[tokio::test]
async fn test_autofill_txn() -> Result<()> {
let wallet = Wallet::create(None).unwrap();
let mut txn = OfferCreate::new(
wallet.classic_address.clone().into(),
None,
None,
None,
Some(72779837),
None,
Some(1),
None,
None,
None,
XRPAmount::from("1000000").into(),
IssuedCurrencyAmount::new(
"USD".into(),
"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq".into(),
"0.3".into(),
)
.into(),
None,
None,
);
let client = AsyncWebsocketClient::<SingleExecutorMutex, _>::open(
"wss://testnet.xrpl-labs.com/".parse().unwrap(),
)
.await
.unwrap();
{
let txn1 = &mut txn;
autofill(txn1, &client, None).await.unwrap();
}
println!("{:?}", txn);
Ok(())
}
I figured that when I have autofill
in a separate scope, the mutable reference txn1
gets dropped after the autofilling is complete and I can then borrow txn
immutable again to print it.
I thought so because of the following code snipped from the book:
let mut s = String::from("hello");
{
let r1 = &mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &mut s;
You can also view the complete code on github.