0
(高),我有一個關於在鏽仿製藥拖的問題:參數可變性
1 - 我想端口一些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
}
這裏我想要的是當T是可變的時,x()和y()返回一個對可變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());
}
任何清潔的方式?
謝謝,我更新了我的答案。 – BigEpsilon 2014-11-22 12:01:07
有趣的是,「Index」/'IndexMut'和'Deref' /'DerefMut'有一定程度的參數可變性,所以可以認爲Rust已經傾倒了腳趾。 – 2014-11-22 18:10:51