(嗨),我有关于铁锈仿制品的两个问题:
1-I尝试将一些C ++类似概念移植到生锈(这里是一个带有2D点的示例):
#![feature(associated_types)]
pub trait Point2D {
type value_type;
fn x(&self) -> &<Self as Point2D>::value_type;
fn y(&self) -> &<Self as Point2D>::value_type;
}
#[deriving(Show)]
pub struct Point2<T> {
x : T,
y : T,
}
impl<T> Point2D for Point2<T> {
type value_type = T;
#[inline]
fn x(&self) -> &T {
&self.x
}
#[inline]
fn y(&self) -> &T {
&self.y
}
}
fn main(){
let mut p = Point2{x: 0i32, y : 0i32};
println!("p = {}", p);
//*p.x() = 1i32; //error: cannot assign to immutable dereference of `&`-pointer
}
这里我想要的是x()和y()在T是可变的时返回对可变T的引用,否则是不可变引用? 我看到一些内部人员谈论参数可变性,但我没有找到任何已建立的RFC。
2-是否有计划在数值(例如template<size_t n>
)上添加参数化以生锈?
感谢
更新:所以我现在唯一的解决方案就是这样:
#![feature(associated_types)]
pub trait Point2D {
type value_type;
fn x_as_mut(&mut self) -> &mut <Self as Point2D>::value_type;
fn y_as_mut(&mut self) -> &mut <Self as Point2D>::value_type;
fn x_as_ref(&self) -> &<Self as Point2D>::value_type;
fn y_as_ref(&self) -> &<Self as Point2D>::value_type;
}
#[deriving(Show)]
pub struct Point2<T> {
x : T,
y : T,
}
impl<T> Point2D for Point2<T> {
type value_type = T;
#[inline]
fn x_as_mut(&mut self) -> &mut T {
&mut self.x
}
#[inline]
fn y_as_mut(&mut self) -> &mut T {
&mut self.y
}
#[inline]
fn x_as_ref(&self) -> &T {
&self.x
}
#[inline]
fn y_as_ref(&self) -> &T {
&self.y
}
}
trait Channel {
}
fn main(){
let mut p1 = Point2{x: 0i32, y : 0i32};
println!("p1 = {}", p1);
*p1.x_as_mut() = 1i32;
println!("p1 = {}", p1);
let p2 = Point2{x:0u8, y:10u8};
println!("p2 = {}", p2.y_as_ref());
}
任何更清洁的方式?
答案 0 :(得分:2)
没有参数可变性。我知道有几个人表达了对这些某事的强烈愿望,但我还没有意识到任何实际的计划。
也没有通用值参数。我相信核心团队肯定想要它,但它现在不是一个优先事项。