diff options
author | garhve <git@garhve.com> | 2023-01-03 19:05:48 +0800 |
---|---|---|
committer | garhve <git@garhve.com> | 2023-01-03 19:05:48 +0800 |
commit | faa108dc5c84f5c4aecee35a2f490eeedc85cb0d (patch) | |
tree | 30193abd2dceb21aab9a536f786f959dedd018f1 /rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type | |
parent | 0e89468188b9d347495dad5b98af137e5f477432 (diff) |
add files
Diffstat (limited to 'rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type')
-rw-r--r-- | rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/Cargo.toml | 8 | ||||
-rw-r--r-- | rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/src/main.rs | 45 |
2 files changed, 53 insertions, 0 deletions
diff --git a/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/Cargo.toml b/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/Cargo.toml new file mode 100644 index 0000000..8f1e556 --- /dev/null +++ b/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "generic-type" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/src/main.rs b/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/src/main.rs new file mode 100644 index 0000000..8a3ef34 --- /dev/null +++ b/rust/theBook/chapter-10-generic-types-traits-lifetimes/generic-type/src/main.rs @@ -0,0 +1,45 @@ +#[derive(Debug)] +struct Point<T, U> { + x: T, + y: U, +} + +// T and U are declared for impl for it goes with struct +impl<T, U> Point<T,U> { + fn new(value: T, v: U) -> Self { + Point {x: value, y: v} + } + + // X1 and Y1 are only relavent to method mixup + fn mixup<X1, Y1>(self, other: Point<X1, Y1>) -> Point<T,Y1> { + Point {x: self.x, y: other.y} + } +} + +fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T { + let mut largest = &list[0]; + + for item in list { + if largest < item { + largest = item; + } + } + largest +} + +fn main() { + let x = [1,3,5,7,9]; + let y = ['a','b','c','d','e']; + + let result = largest(&x); + println!("{result}"); + + let result = largest(&y); + println!("{result}"); + + let result = Point::new(3.5,7); + println!("{},{}",result.x, result.y); + + let result = result.mixup(Point::new("hello",'c')); + println!("{},{}",result.x, result.y); +} |