From e Into en Rust
Implementa From y obtienes Into gratis, en ambas direcciones de la llamada.
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
}
fn report(temp: impl Into<Fahrenheit>) -> String {
format!("{:.1}F", temp.into().0)
}
fn main() {
let f = Fahrenheit::from(Celsius(100.0));
println!("{:.1}", f.0);
let also: Fahrenheit = Celsius(0.0).into();
println!("{:.1}", also.0);
println!("{}", report(Celsius(21.5)));
}
Cómo funciona
Fromconvierte un valor propio en tu tipo..into()es la misma conversión, elegida por el tipo destino.- Las funciones genéricas toman
impl Into<T>para aceptar ambos.
Palabras clave y builtins usados aquí
FromIntoStringf64fnforimplletstruct
El intento, en números
- Líneas
- 21
- Caracteres a escribir
- 429
- Tokens
- 143
- Ritmo de tres estrellas
- 105 tpm
Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 82 segundos.
Paso 1 de 4 en Traits estándar; paso 8 de 19 en Traits y genéricos.