I have added the 'static lifetime in an attempt to cure the persistent lifetime problems with acc.
Within this function I attempt to write out acc:
....
let awt_writer_task = task::spawn(
async {
let bufstr = acc.to_string();
let bytes = bufstr.into_bytes();
let mut file = File::create("data/awt.cfg")
.await
.expect("Failed to open accountfile for writing");
file.write_all(&bytes[..])
.await
.expect("failed to write to accountfile");
file.flush()
.await
.expect("failed to flush buffer to accountfile");
}
);
... then I do some more work, hopefully while this writes asynchronously, and at the end of the body of trade I have:
task::block_on(awt_writer_task);
Ok(())
} // end of trade
and I get these errors, both on reading and writing
error[E0597]: `acc` does not live long enough
--> src/main.rs:305:17
|
304 | async {
| _________-_____-
| |_________|
| ||
305 | || let bufstr = acc.to_string();
| || ^^^ borrowed value does not live long enough
306 | || let bytes = bufstr.into_bytes();
307 | || let mut file = File::create("data/awt.cfg")
... ||
315 | || .expect("failed to flush buffer to accountfile");
316 | || }
| || -
| ||_________|
| |__________value captured here by generator
| argument requires that `acc` is borrowed for `'static`
...
360 | } // end of trade
| - `acc` dropped here while still borrowed
error[E0597]: `acc` does not live long enough
--> src/main.rs:372:4
|
371 | async {
| _________-_____-
| |_________|
| ||
372 | || acc = areadaccount(&accfile)
| || ^^^ borrowed value does not live long enough
373 | || .await
374 | || .expect("areadaccount failed to open/read accountfile");
375 | || }
| || -
| ||_________|
| |__________value captured here by generator
| argument requires that `acc` is borrowed for `'static`
...
385 | }
| - `acc` dropped here while still borrowed
I am thinking I may have to create two static copies of "acc", one just for input and another one for output and just copy all the unchanged items across. That would get rid of the mutability. Might that help? It seems awkward though and violating the Rust principle of: "could not write it better by hand".
As written, this requires borrowing acc into the future. However since to_string creates a copy, you can just do that before creating the async block.
I recommend cloning it outside the async block, and making the block move so it takes ownership of bufstr.
Note that asynchronous code is lazy! It does not start running until you poll it, so if you want to start it earlier, you must spawn it when you want it to start.
If you wish to spawn it, do other work, and later wait for it to finish, you can store the JoinHandle returned from spawn and later use block_on on the handle.
If you intend to modify it from inside the asynchronous code, that is typically very difficult as you run into threading and synchronization problems. I recommend moving a clone of acc into the future, modifying that, returning it from the task, and using the fact that the join handle returns it to obtain the new value in your synchronous code, where you then modify the mutable variable.
As I understand it, in async-std, and my code above, the task in the async block is spawned with task::spawn and thus starts running its .awaits right away.
Anyway, thank you all for your help. It was a steep learning curve but I think I got there in the end.
The solution to the problem with the given code was a combination of two tricks:
a) using "move"
b) making sure that the moved item is not an argument passed to the enclosing function
I still do not quite understand why the restriction b) is necessary, even when the item is not mutable and not being changed anywhere but at least I got it working by somewhat wasteful local cloning.
The reason you have to transfer ownership when using spawn is that the signature of that function requires 'static. This is because the spawned future might outlive your function, so it cannot have any references to the local stack.
This restriction is not in place on block_on because the future is guaranteed to have stopped when the function returns, meaning the references live long enough.
If you wish to block on several tasks you must use join to combine them into one and call block on on that. Unfortunately the API does not allow performing synchronous operations meanwhile waiting for the future.
One very common method of having a reference to the same object in several 'static tasks is to use referece counting. The reason this works is that the object lives until every reference has been dropped, so there is no real owner that must live longer than the others. However be aware that you cannot add reference counting to objects you don't own, so if you're given something in an argument, it must already be reference counted in order to use this technique (or you can make one copy and reference count that, I guess).
Thank you for that erudite information. I find with Rust generally, that there is usually a way of doing mostly anything. However, knowing about it is quite another matter, as there are so many complex rules and mechanisms.
and I get:
.recv_json().await?;
| ^ doesn't have a size known at compile-time
plus lots of gobblygook from the compiler.
It has got to be something simple, right? What am I doing wrong?
PriceStruct is the JSON structure, I was able to read it previously using std::io::stdin
and convert it using serde_json.
I can not find anything in the surf documentation on how exactly to set the headers and receive JSON through get request, a common enough task?
It seems you already have the function calls needed? Can you post some more details, perhaps the error says which type is causing issues with unknown sizes?
The error complains about recv_json().await; My JSON type has a VEC in it (unknown number of items) but surely this should be capable of being read, as it was previously by std::io:stdin?
I am not sure if I am using the .set_header correctly in combination with recv_json(). Examples and docs only mention one at a time.
The E0282 error is what happens when the compiler can't figure out what the type of something should be. Note that this is different fro the “doesn't have a size known at compile-time” error, so are you getting more than one error perhaps?
Aha! In that case it's probably because it can't figure out which error type to use! The pitfall is that ? will convert errors using the From trait. This is very convenient because it allows you to use ? to return an error type such as Box<dyn Error> even though the returned error is something else, e.g. std::io::Error, but it can sometimes cause type inference issues.
If you have two consecutive conversions, e.g. a ? in a closure and then another ? outside the closure, it knows the starting type and the ending type, but because you used ? twice, it converts twice, and doesn't know which type to put in the middle. For example: std::io::Error -> ??? -> Box<dyn Error>.
Of course, there are other things than ? that perform conversions, but this is the most common place where this problem comes up.
Typically this can be solved by telling it to use either the starting or ending type in the middle conversion.