These are chat archives for rust-lang/rust

24th
Mar 2019
silmanduin66
@silmanduin66
Mar 24 13:28
i have a function which takes two vector of str as parameter and returns a vector of str
is this the right way to do it
fn my_function<'a>(v: &'a [&str], t: &'a [&str]) -> &'a [&'a str]{

    // do something

    // return something
}
Denis Lisov
@tanriol
Mar 24 13:31
Pretty sure the return value should, at least, be Vec<_> (whether it should be a Vec<&'a str> or Vec<String> or Vec<Cow<'a, str>> depends on what you're doing to them)
silmanduin66
@silmanduin66
Mar 24 13:36

could you explain me the differrence between :

fn my_function<'a>(v: &'a [&str], t: &'a [&str]) -> &'a [&'a str] { // ... }

and

fn my_function<'a>(v: Vec<&'a str>, t: Vec<&'a str>) -> Vec<&'a str> { // ... }
red75prime
@red75prime
Mar 24 13:43
First function can return v, t, or &'static [&'static str] only.
Denis Lisov
@tanriol
Mar 24 13:43
Or some subslice of one of the arguments.
When you return &str instead of a String, you cannot really modify it, just select a part of the string that you need.
When you return &[T] instead of Vec<T>, you cannot really choose which elements you return - just a slice of one of the arguments (or of something that lives forever).
silmanduin66
@silmanduin66
Mar 24 14:08
ok thanks
Björn Harrtell
@bjornharrtell
Mar 24 16:08

Rust newbie here and not surprisingly stuck with borrow issues. Using rusoto_ec2 crate to query AWS, I've gotten past some simple cases and can list my "instances". Each instance got a Vec<Tag> where each Tag is a struct with a key and value, both Option<String>. I want to get the first value where the key is equal to "Name", but I get into cannot move out of borrowed content.

While this line of code works to find the first tag with any key:

let tag_with_key = tags.iter().find(|t| t.key.is_some());

This one fails with cannot move out of borrowed content and I do not understand why:

let name_tag = tags.iter().find(|t| t.key.filter(|k| k == "Name").is_some());

Both help in finding out what I'm not understanding and if there is another way of doing what I want would be appriciated.

Denis Lisov
@tanriol
Mar 24 16:44
The problem here is that the Option::filter method takes the option by value, not by reference.
I'd probably write the condition as
|t| t.key.as_ref().map(|k| &**k) == Some("Name")
Denis Lisov
@tanriol
Mar 24 16:50
Or even more explicit
|t| t.key.as_ref().map(|k| k.as_str()) == Some("Name")
Björn Harrtell
@bjornharrtell
Mar 24 17:41
@tanriol: thanks, make sense and works - now I just have to understand more borrow issues later in the process.. :)
Brian Knapp
@knappador
Mar 24 17:56
When you throw something inside an Arc, does it get a heap allocation implied or might some Arc's fragment memory lower in a thread's stack?
Michal 'vorner' Vaner
@vorner
Mar 24 17:59
Arc heap-allocates.
matrixbot
@matrixbot
Mar 24 17:59
bspeice Gets moved into a heap segment.