Funzione generica con trait bound in Rust
Livello 4165 battiture
Le funzioni generiche con limiti di trait possono accettare qualsiasi tipo che implementa il trait specificato.
Codice Rust
// use std::fmt::Display importa il trait Display1use std::fmt::Display;// Funzione generica: T: Display significa che T deve implementare il trait Display// Così value può essere di qualsiasi tipo che {} sa formattare2fn print_value<T: Display>(value: T) { // {} usa il trait Display per formattare value3 println!("Value: {}", value);4}// fn main() è il punto di ingresso5fn main() { // Chiama con i32, che implementa Display6 print_value(42); // Chiama con &str, che implementa Display7 print_value("hello"); // Chiama con f64, che implementa Display8 print_value(3.14);9}Output
Value: 42 Value: hello Value: 3.14
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Rust e quante volte compaiono.
:× 7(× 6)× 6;× 5_× 4"× 4{× 3}× 3,× 1!× 1