是否可以声明代表特征的关联类型?如果没有,我该怎么办呢?试着做:
struct ColorData {
let name: String
let value: UIColor
}
class MyViewController: UIViewController {
let data = [
ColorData( name: "Blue", value: UIColor.blueColor() ),
ColorData( name: "Red", value: UIColor.redColor() ),
ColorData( name: "Green", value: UIColor.greenColor() )
]
@IBOutlet weak var label: UILabel!
var timer = NSTimer()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear( animated )
self.timer = NSTimer.scheduledTimerWithTimeInterval( 1.0, target: self, selector: "update", userInfo: nil, repeats: true )
}
func update() {
let randomIndex = Int(arc4random() % UInt32(self.data.count))
let colorData = data[ randomIndex ]
self.label.text = colorData.name
self.label.textColor = colorData.value
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear( animated )
// Don't forget to invalidate, otherwise this instance of `MyViewController` will leak
self.timer.invalidate()
}
}
我遇到的最大问题是使用trait Foo {
/// A trait representing all types that can be returned from baz()
type ReturnType;
fn baz(&self) -> Self::ReturnType;
}
特征,因为我想要一个函数来返回实现Sized
的类型项的向量:
ReturnType
选项1的问题是trait Foo {
type ReturnType;
// option 1
fn bar(&self) -> Vec<Self::ReturnType>;
// option 2
fn bar<T: Self::ReturnType>(&self) -> Vec<T>;
}
不会被调整大小,因为它是一个特征,而选项2的问题是编译器不会将关联的类型识别为特征:ReturnType
和failed to resolve. Use of undeclared type or module 'Self'
(这使我认为相关类型不能指定特征)
编辑:我正在尝试做的一个例子
use of undeclared trait name 'Self::ReturnType'
用户的实施可能是
/// Represents all types that store byte-data instead of the actual
/// element
trait BufferedVec {
/// the trait representing types that can be converted from the byte-data
type FromBuffer;
/// return the data at the given index, converted into a given type
fn get<T: Self::FromBuffer>(&self, index: usize) -> T;
}
答案 0 :(得分:2)
关联类型无法指定特征。您无法在Rust中的任何位置指定特征。您可以要求通用参数(或关联类型)需要实现特征。
trait Foo {
type ReturnType: Clone;
}
这样Foo
的任何实现者都需要确保他们选择的ReturnType
也实现了Clone
。
impl Foo for Bar {
type ReturnType: i32;
}