可以强迫&mut T
进入,&T
但是如果在类型构造函数中发生类型不匹配,则无法使用。
use ndarray::*; // 0.13.0
fn print(a: &ArrayView1<i32>) {
println!("{:?}", a);
}
pub fn test() {
let mut x = array![1i32, 2, 3];
print(&x.view_mut());
}
对于上面的代码,我得到以下错误:
|
9 | print(&x.view_mut());
| ^^^^^^^^^^^^^ types differ in mutability
|
= note: expected reference `&ndarray::ArrayBase<ndarray::ViewRepr<&i32>, ndarray::dimension::dim::Dim<[usize; 1]>>`
found reference `&ndarray::ArrayBase<ndarray::ViewRepr<&mut i32>, ndarray::dimension::dim::Dim<[usize; 1]>>`
可以强制&mut i32
使用&i32
,为什么不将其应用于这种情况?您能否提供一些示例,说明如何可能适得其反?
考虑对此空字符串进行检查,该空字符串依赖于函数content
运行时保持不变is_empty
(仅出于说明目的,请勿在生产代码中使用此字符串):
struct Container<T> {
content: T
}
impl<T> Container<T> {
fn new(content: T) -> Self
{
Self { content }
}
}
impl<'a> Container<&'a String> {
fn is_empty(&self, s: &str) -> bool
{
let str = format!("{}{}", self.content, s);
&str == s
}
}
fn main() {
let mut foo : String = "foo".to_owned();
let container : Container<&mut String> = Container::new(&mut foo);
std::thread::spawn(|| {
container.content.replace_range(1..2, "");
});
println!("an empty str is actually empty: {}", container.is_empty(""))
}
由于&mut String
不强制转换为,因此该代码无法编译&String
。但是,如果确实如此,则新创建的线程可能会content
在format!
调用之后但在is_empty
函数中的相等比较之前更改,从而使容器内容是不可变的假设无效,这是空检查所必需的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句