# Trait

前言

声明 trait 的关键字。trait 定义了一组行为,可由多个类型实现。(有点像原型方法)

# 1.定义trait

# 1.1 trait 基础

trait Circle {
    fn get_width(&self)->i32
    fn get_height(&self) ->i32
}
struct Value {
    width:i32,
    height:i32
}
impl Value {
    fn new(widht:i32,height:i32)->Self{
        Self{
            width,
            height
        }
    }
}
impl Circle for Value {
    fn get_width(&self)->i32{
        self.width
    }
    fn get_height(&self)->i32{
        self.height
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main(){
    let  value =Value::new(12,13);
    value.get_width();
}
1
2
3
4

# 1.2 trait 默认方法

trait Circle {
    fn get_width(&self)->i32
    fn get_height(&self) ->i32{
        self.width*2
    }
}
1
2
3
4
5
6

# 2.常用的 trait

# 2.1 语言扩展 trait

# 2.2 标记行 trait

# 2.3 普通 trait

# 3.参数

# 3.1 AsRef

# 3.2 AsMut

# 4.转换

# From

# Into

# TryFrom

# TryInto

# 泛型