# Using async-std (was reqwest)

**URL:** <https://users.rust-lang.org/t/using-async-std-was-reqwest/32735>\
**Category:** help\
**Created:** [September 20, 2019, 1:42am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735 "2019-09-20T01:42:23Z")\
**Posts on this page:** 15\
**Page:** 2

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 23, 2019, 11:17pm UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/22 "2019-09-23T23:17:53Z")

</div>

I read a mutable struct "acc", modify it, and write it back. For example, on the output side, I have a function with this heading:

```
fn trade( dats:&DatStruct, acc:&'static mut AccStruct, basefile:&str, accountfile:& str )	
-> Result<(), Box<dyn Error>> {

```

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".

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 24, 2019, 5:49am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/24 "2019-09-24T05:49:53Z")

</div>

> [@Rustafarian](#):
>
> ```rust
> let bufstr = acc.to_string();
> 
> ```

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`.

> [@Rustafarian](#):
>
> then I do some more work, hopefully while this writes asynchronously, and at the end of the body of trade I have

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`](https://docs.rs/async-std/0.99.6/async_std/task/struct.JoinHandle.html) 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.

---

<div class="post-metadata">

**Author:** ![pickfire](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/pickfire/32/7102_2.png) [@pickfire](https://users.rust-lang.org/u/pickfire)\
**Post date:** [September 24, 2019, 4:57pm UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/25 "2019-09-24T16:57:58Z")

</div>

@Rustafarian if you come from a javascript or go background, [Futures Concurrency I: Introduction](https://blog.yoshuawuyts.com/futures-concurrency/) does a good comparison between different offerings of `async/await`.

> [@alice](#):
>
> > then I do some more work, hopefully while this writes asynchronously, and at the end of the body of trade I have
> 
> 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.

Summarized as reminder, rust `Future`s are _pull based_ rather than _push based_. So it is only start when `.await` happens.

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 24, 2019, 9:41pm UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/26 "2019-09-24T21:41:22Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 24, 2019, 10:40pm UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/27 "2019-09-24T22:40:31Z")

</div>

The reason you have to transfer ownership when using [`spawn`](https://docs.rs/async-std/0.99.6/async_std/task/fn.spawn.html) 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`](https://docs.rs/async-std/0.99.6/async_std/task/fn.block_on.html) 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](https://doc.rust-lang.org/std/sync/struct.Arc.html). 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).

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 25, 2019, 12:32am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/28 "2019-09-25T00:32:33Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 28, 2019, 7:18am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/29 "2019-09-28T07:18:15Z")

</div>

I am trying to use surf now. I have this fragment of code:

> async fn gethtprice() -\> Result\<(DatStruct), Box\> {  
> let price:PriceStruct = surf::get(url)  
> .set\_header("Authorization",auth)  
> .recv\_json().await?;

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?

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 28, 2019, 8:03am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/30 "2019-09-28T08:03:19Z")

</div>

> [@Rustafarian](#):
>
> I can not find anything in the surf documentation on how exactly to set the headers and receive JSON through get request.

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?

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 28, 2019, 8:17am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/31 "2019-09-28T08:17:46Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 28, 2019, 8:33am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/32 "2019-09-28T08:33:15Z")

</div>

There shouldn't be any issues with a Vec. Are you using traits in suspicious places anywhere? Can you post some more code?

I'd like to hear the gobblygook from the compiler too

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 28, 2019, 8:42am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/33 "2019-09-28T08:42:06Z")

</div>

Can not infer type. The gobblygook was explanation of this error E0282

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 28, 2019, 8:46am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/34 "2019-09-28T08:46:21Z")

</div>

The [E0282](https://doc.rust-lang.org/error-index.html#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?

---

<div class="post-metadata">

**Author:** ![Rustafarian](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustafarian/32/12690_2.png) [@Rustafarian](https://users.rust-lang.org/u/Rustafarian)\
**Post date:** [September 28, 2019, 9:33am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/35 "2019-09-28T09:33:29Z")

</div>

Thanks @alice, I think I "solved" it, by using .expect(.....) instead of .?, usually found in examples. It is a minefield 😉

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [September 28, 2019, 12:04pm UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/36 "2019-09-28T12:04:51Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [December 30, 2019, 3:10am UTC](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735/38 "2019-12-30T03:10:49Z")

</div>

Closed on December 30, 2019, 3:10am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

[Previous page](https://users.rust-lang.org/t/using-async-std-was-reqwest/32735.md?page=1)
