[英]Converting a String to an &str Rust without resulting in borrowing problem
Is there someway to convert a String (function parameter) into &str (used in return value) while avoiding borrowing problems or referencing a temporary value.有没有办法将字符串(函数参数)转换为 &str(用于返回值),同时避免借用问题或引用临时值。
Here is an example use case:这是一个示例用例:
PS: I am constrained by existing functions to these types and cannot just change the type of the function's parameter nor its &str consuming return value. PS:我受到这些类型的现有函数的限制,不能只更改函数参数的类型,也不能更改它的 &str 消耗返回值。 Also the following example uses clap::Arg::new to emphasize this aspect.
以下示例还使用 clap::Arg::new 来强调这一方面。
// f is any iterator over String values, for example sake I am using Vec<String> with literal value which does not represent the real case.
let f: Vec<String> = vec!["A".into(),"B".into(),"C".into()].into_iter();
let arg: clap::Arg = f.map(|s: String|{
clap::Arg::new(s.as_str())
});
Is there someway to convert a String (function parameter) into &str (used in return value) while avoiding borrowing problems or referencing a temporary value.
有没有办法将字符串(函数参数)转换为 &str(用于返回值),同时避免借用问题或引用临时值。
No but yes, but, really, no.不但是是的,但是,真的,不。
"No": if your parameter is a String
, then the function owns the String
, meaning once the function exits the String
will be reclaimed, and so any referenced to that would be invalid as it would be dangling. “否”:如果您的参数是
String
,则 function 拥有String
,这意味着一旦 function 退出String
将被回收,因此任何引用它的内容都将无效,因为它会悬空。
"but yes": you can convert the String
into a Box<str>
, which you can thenleak
. “但是是的”:您可以将
String
转换为Box<str>
,然后您可以将其leak
。 This returns a &'static str
, which will live forever这将返回一个
&'static str
,它将永远存在
"but, really, no": while leaking memory is safe as far as Rust is concerned, it's still leaking memory . “但是,真的,不”:虽然泄漏 memory 就 Rust 而言是安全的,但它仍在泄漏 memory 。 This might be fine in some contexts (eg short-running processes where explicitly freeing is a waste of resources, or some forms of ad-hoc interning), but in general it's really bad practice.
这在某些情况下可能很好(例如,显式释放是浪费资源的短期运行进程,或者临时实习的一些 forms),但总的来说,这确实是一种不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.