英文:
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<String> out of this line, for example, so that from a string type "home/user/project" to get vec!["home/", "user/", "project"] 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<(there should be a type of String, but it turns out ())> = dir.split('/').map(|s| s.to_string().push('/')).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<_> = dir.split_inclusive('/')
.map(String::from)
.collect();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论