1饺藤、trait 泛型
使用trait 方法實現(xiàn)泛型參數(shù)的初始化例:
use std::fmt::Debug;
use serde::Serialize;
trait Result<T> {
fn ok(data: T) -> Self;
fn ng(code: i32, msg: String) -> Self;
}
#[derive(Serialize, Debug)]
struct BaseResult<T> {
code: i32,
message: String,
data: Option<T>,
}
impl<T> Result<T> for BaseResult<T> {
fn ok(data: T) -> Self {
BaseResult {
code: 0,
message: "OK".to_string(),
data: Some(data),
}
}
fn ng(code: i32, message: String) -> Self {
BaseResult { code, message, data: None }
}
}
fn main() {
let a = BaseResult::<String>::ok("Nice Data".to_string());
let str = serde_json::to_string(&a).unwrap();
println!("{}", str);
let b = BaseResult::<u32>::ng(1, "not allowd".to_string());
let b_str = serde_json::to_string(&b).unwrap();
println!("{}", b_str);
}
2剑辫、trait 對象
trait Speak {
fn speak(&self);
}
struct Dog;
impl Speak for Dog {
fn speak(&self) {
println!("Woof!");
}
}
struct Cat;
impl Speak for Cat{
fn speak(&self) {
println!("Meow!");
}
}
fn main() {
let animals:Vec<Box<dyn Speak>> = vec![
Box::new(Dog),
Box::new(Cat),
];
for animal in animals {
animal.speak();
}
}
3饼问、Send, Sync
4、格式化
5揭斧、 Copy Clone
6莱革、 定義無字段的 struct ,通過下標來訪問
struct MyBox<T>(T);
struct YourBox<T, R>(T, R);
fn main() {
let a = MyBox(18);
let b = YourBox("AA", 18);
println!("{}", a.0);
println!("{} - {}", b.0, b.1);
}