This question is on lifetimes for arguments to the aws_sdk_s3::Region::new
constructor (Region in aws_sdk_s3 - Rust)
I have an async function that has a parameter: region: Option<&str>
This simplified line gives a compiler error: let x = aws_sdk_s3::Region::new(region.unwrap());
error[E0521]: borrowed data escapes outside of function
--> aws_s3.rs:65:17
|
37 | region: Option<&str>,
| ------ - let's call the lifetime of this reference `'1`
| |
| `region` is a reference that is only valid in the function body
...
65 | let x = aws_sdk_s3::Region::new(region.unwrap());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `region` escapes the function body here
| argument requires that `'1` must outlive `'static`
For more information about this error, try `rustc --explain E0521`.
First, I don't see how the variable escapes the function body anyway, nothing created in that function is outlasting the function body, and in the simplified example, x
was never used again.
Second, can I be right in thinking that the AWS api is expecting only static string references? That would be incredible.
Yet a simple change to use to_owned()
:
- let x = aws_sdk_s3::Region::new(region.unwrap().to_owned());
+ let x = aws_sdk_s3::Region::new(region.unwrap());
will apparently resolve this error.
The result of to_owned()
is surely a heap-allocated string with a slightly shorter lifetime than the original parameter, so why would it fix the problem?
Surely it could not be that the parameter only lasts up till the first async/await call?
The documentation for Region constructor is: Region in aws_sdk_s3 - Rust and shows that it takes region: impl Into<Cow<'static, str>>
and I'm not quite sure what one of those is. Is it the str
that is required to be 'static
?
In passing a str.to_owned()
which I understand emits a heap allocates string, does that become owned by the Region instance or is it destroyed when the Region constructor returns?
I didn't use the from_static
constructor because I'm sure my argument is not a region: &'static str
What am I missing?