"首次提交"
This commit is contained in:
1
generics/.gitignore
vendored
Executable file
1
generics/.gitignore
vendored
Executable file
@ -0,0 +1 @@
|
||||
/target
|
9
generics/Cargo.toml
Executable file
9
generics/Cargo.toml
Executable file
@ -0,0 +1,9 @@
|
||||
workspace = { members = ["trait_learn"] }
|
||||
[package]
|
||||
name = "generics"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
68
generics/src/main.rs
Executable file
68
generics/src/main.rs
Executable file
@ -0,0 +1,68 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
generics();
|
||||
generics1();
|
||||
}
|
||||
|
||||
|
||||
fn generics() {
|
||||
// 定义一个支持多种类型的结构体,元素的类型取决于实际代码
|
||||
struct Point <T, U> {
|
||||
x:T,
|
||||
y:U,
|
||||
}
|
||||
let p1 = Point {
|
||||
x : 10, //i32
|
||||
y : 'c', //char
|
||||
};
|
||||
let p1 = Point {
|
||||
x : 10, //i32
|
||||
y : 10.3, // f64
|
||||
};
|
||||
let p1 = Point {
|
||||
x : '1', // char
|
||||
y : 10.3, // f64
|
||||
};
|
||||
}
|
||||
|
||||
fn generics1() {
|
||||
#[derive(Debug)]
|
||||
struct Point <T, U> {
|
||||
x:T,
|
||||
y:U,
|
||||
}
|
||||
|
||||
//对于point的实现也使用泛型,
|
||||
/* 这里impl后加 <T, U> 是因为后续的Point里面指定的类型T,U就是由此来的
|
||||
而这里不加V和W是因为V和W是函数mixup中才使用的并不是和Point有关的泛型,所以不需要再这里加T和U,
|
||||
泛型的顺序是没关系。仅仅是为了指明有哪些类型。使用时对应即可
|
||||
*/
|
||||
impl<T, U> Point<T, U> {
|
||||
//impl<U, T> Point<T, U> { // 这是正确的
|
||||
//impl<T, U, V, W> Point<T, U> { //这是错误的
|
||||
fn new(x:T, y:U) -> Point<T, U>{
|
||||
Point{
|
||||
x,
|
||||
y,
|
||||
}
|
||||
}
|
||||
|
||||
//这里使用了泛型V和W是为了有别于上面的T和U,因为self的类型已经是T和U了,
|
||||
//如果这里还是T和U那么其实就是限制了other的类型,必须是和self一样的类型
|
||||
//这里使用V和W就是表示可以是任意的类型。
|
||||
//返回值是T和W就是说明他用的是self的x和other的Y
|
||||
//fn mixup <I, V, W>(self, other: Point<V,W>, z:I) -> Point<T,W>{ // 有其他参数就继续加泛型名即可
|
||||
fn mixup <V, W>(self, other: Point<V,W>) -> Point<T,W>{
|
||||
Point{
|
||||
x:self.x,
|
||||
y:other.y,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let point = Point::new(32, 'a');
|
||||
let point1 = Point::new(23.0, 100);
|
||||
|
||||
let point2 = point1.mixup(point);
|
||||
println!("{:?}", point2);
|
||||
}
|
Reference in New Issue
Block a user