在Rust中向每个向量元素添加一个符号(或一组符号)

huangapple go评论63阅读模式
英文:

Adding a symbol (or group symbols) to each Vector element on Rust

问题

let dir: String = env::current_dir().unwrap().display().to_string();

接下来,我需要将这行代码转换成Vec<String>,例如,将字符串类型"home/user/project"转换成vec!["home/", "user/", "project"] as String

我尝试了一些选项,但不断出现类型错误和其他问题。但在我看来,其中一个选项最接近的是:

let dir_split: Vec<String> = dir.split('/').map(|s| s.to_string()).collect();
英文:

What is my problem?
I get the current directory with the help

let dir: String = env::current_dir().unwrap().display().to_string();

Next, I need to make Vec&lt;String&gt; out of this line, for example, so that from a string type &quot;home/user/project&quot; to get vec![&quot;home/&quot;, &quot;user/&quot;, &quot;project&quot;] as String.

I tried a couple of options, but there are constantly errors of types and much more, but one of my options, which, in my opinion, was closest to

let dir_split: Vec&lt;(there should be a type of String, but it turns out ())&gt; = dir.split(&#39;/&#39;).map(|s| s.to_string().push(&#39;/&#39;)).collect();

答案1

得分: 0

使用str::split_inclusive而不是str::split,这样你就不需要手动push,这是导致问题的原因。

当你使用map时,你将每个值映射到表达式返回的值。在这种情况下,这将是String::push,它返回()

let var: Vec<_> = dir.split_inclusive('/')
    .map(String::from)
    .collect();
英文:

Instead of str::split use str::split_inclusive which would mean you don’t need to manually push, which is causing you issues.

When you use map, you are mapping each value to the the value returned by the expression. In this case, this would be String::push, which is returns ().

let var: Vec&lt;_&gt; = dir.split_inclusive(&#39;/&#39;)
    .map(String::from)
    .collect();

huangapple
  • 本文由 发表于 2023年7月20日 21:09:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定