Trovo questo è particolarmente utile modello per consentire overloading dei metodi:C'è qualche svantaggio nel sovraccaricare le funzioni in ruggine usando un tratto e una funzione generica?
struct Foo {
value:uint
}
trait HasUIntValue {
fn as_uint(self) -> uint;
}
impl Foo {
fn add<T:HasUIntValue>(&mut self, value:T) {
self.value += value.as_uint();
}
}
impl HasUIntValue for int {
fn as_uint(self) -> uint {
return self as uint;
}
}
impl HasUIntValue for f64 {
fn as_uint(self) -> uint {
return self as uint;
}
}
#[test]
fn test_add_with_int()
{
let mut x = Foo { value: 10 };
x.add(10i);
assert!(x.value == 20);
}
#[test]
fn test_add_with_float()
{
let mut x = Foo { value: 10 };
x.add(10.0f64);
assert!(x.value == 20);
}
C'è qualche aspetto negativo significativo per fare questo?
Se la funzione "sovraccarico" deve funzionare su un oggetto che può fare, utilizzare un tratto. In caso contrario, sarebbe meglio eseguire il casting in precedenza o utilizzare più funzioni. –
Ryan
Uno può anche diventare più folle: doppia spedizione. guarda come è fatto l'hashing in Rust. – sellibitze