简体   繁体   English

在 Rust 的 2 Vec 中有相同的字符串?

[英]Having same String in 2 Vec in Rust?

Not sure if this is best title for my question, if there is better, please suggest.不确定这是否是我问题的最佳标题,如果有更好的,请提出建议。

This is sample of working code, that is approximation of my real code, but it is fine for demonstration.这是工作代码示例,是我的真实代码的近似值,但它适合演示。

fn main() {
    let data = vec!["a".to_string(), "b".to_string(), "c".to_string(), ];
    
    let mut v1 = Vec::new();
    let mut v2 = Vec::new();
    for i in data {
        v1.push(i.to_owned());
        v2.push(i.to_owned());
    }
    // to make it read-only, so that I do not make same stupid mistake later
    let v1 = v1;
    let v2 = v2;
    
    println!("{:?}", v1);
    println!("{:?}", v2);
}

Basically I have vectors of strings and I need to make N(already 2, but there will be more, around 20) vectors that need to have access to Strings from original vector.基本上我有字符串向量,我需要制作 N(已经有 2 个,但还会有更多,大约 20 个)需要从原始向量访问字符串的向量。

One solution that I have is to use to_owned().我拥有的一种解决方案是使用 to_owned()。 And if I understand it correctly this is basically creating copy of String, so I end up with 2 same Strings in memory, which I find unnecessary wasted and would like to avoid it.如果我理解正确的话,这基本上是在创建 String 的副本,所以我最终在 memory 中得到了 2 个相同的 String,我发现这是不必要的浪费,并希望避免这种情况。

What is best way in Rust to do it? Rust 中最好的方法是什么?

One solution that I have found is to convert original data Vec to &str, but not sure if that is best/correct way to do it in Rust(I am still beginner in Rust).我发现的一种解决方案是将原始数据 Vec 转换为 &str,但不确定这是否是在 Rust 中执行此操作的最佳/正确方法(我仍然是 Rust 的初学者)。

Without any more context on why you need those vectors or what you want to do with them, I see two ways you can take.没有更多关于为什么需要这些向量或你想用它们做什么的上下文,我看到你可以采用两种方法。

  1. Use references使用参考资料

This approach stores the string once in the data variable and stores references to these strings in the other vectors.这种方法将字符串存储在data变量中一次,并将对这些字符串的引用存储在其他向量中。

fn main() {
    let data = vec!["a".to_string(), "b".to_string(), "c".to_string(), ];
    
    let mut v1 = Vec::new();
    let mut v2 = Vec::new();
    for i in &data {
        v1.push(i);
        v2.push(i);
    }
    // to make it read-only, so that I do not make same stupid mistake later
    let v1 = v1;
    let v2 = v2;
    
    println!("{:?}", v1);
    println!("{:?}", v2);
}
  1. Use reference-counting smart pointers使用引用计数智能指针

This approach stores the strings on the heap, and uses the Arc type from the standard library which ensures via reference counting that the string on the heap will be deleted once all vectors have been deleted.这种方法将字符串存储在堆上,并使用标准库中的Arc类型,通过引用计数确保一旦所有向量都被删除,堆上的字符串就会被删除。 The clone operation is cheap, it only increases the reference count.克隆操作很便宜,它只是增加了引用计数。

use std::sync::Arc;

fn main() {
    let data = ["a".to_string(), "b".to_string(), "c".to_string()]
        .into_iter().map(|i| Arc::new(i)).collect::<Vec<_>>();
    
    let mut v1 = Vec::new();
    let mut v2 = Vec::new();
    for i in &data {
        v1.push(Arc::clone(i));
        v2.push(Arc::clone(i));
    }
    // to make it read-only, so that I do not make same stupid mistake later
    let v1 = v1;
    let v2 = v2;
    
    println!("{:?}", v1);
    println!("{:?}", v2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 怎么接受Vec <String> 和Vec <str> 作为Rust中的函数arg - How to accept both Vec<String> and Vec<str> as function arg in Rust 转换 Vec<String> 在 Rust 中放入一片 &amp;str ? - Convert Vec<String> into a slice of &str in Rust? 如何为 Vec 编写计数器 function<string> 在 Rust 中?</string> - How to write a counter function for Vec<String> in Rust? 将 Rust 字符串拆分为其具有连续相同字符的子字符串的 Vec - Splitting a Rust string into a Vec of its substrings with contiguous identical characters 如何模式匹配转换后的 Vec<string> 在 Rust 中?</string> - How to pattern match a transformed Vec<String> in Rust idiomatically? 当在循环内连接 Vec&lt;&amp;str&gt; 元素时字符串覆盖 - rust - string overwriting when concat Vec<&str> element inside loop - rust 将字符串拆分为 Vec 的最佳方法<string>在字符,Rust 中没有环视的其他字符前面没有?</string> - best way to split string into Vec<String> at character, when not preceeded by other character without lookaround in Rust? 字符串在Android中没有相同的值 - String not having same value in Android 遍历文件中的行并从 vec 中查找 substring! 在 rust - Iterating over lines in a file and looking for substring from a vec! in rust 如何转换 Vec<char> 到一个字符串 - How to convert Vec<char> to a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM