Rust - Generics

eslerkang·2022년 3월 16일
0

Rust

목록 보기
9/10
post-thumbnail

Generics

Generics of Rust is same as Typescript's Generics. We can use it to give some freedom of variable type.

fn print_thing<T>(input: T) {
	println!("{}", input);
}

fn main() {
	print_thing(33);
}

We can use Generics "like" this, but not the same.
As we run this code, we can see the error

error[E0277]: `T` doesn't implement `std::fmt::Display`

It means, some value of T type might have no std::fmt::Display implement. If we send Vector to print_thing function, as Vector doesn't implement std::fmt::Display, we cannot execute the println! statement. So we have to restrict our Generics.

use std::fmt::Display;

struct Book {
	year: u8
}

fn give_thing<T: Display>(input: T) -> T {
  println!("{}", input); // std::fmt::Display
  input
}

fn main() {
  let x = give_thing(33);
  let y = give_thing(String::from("haha"));
  println!("{} {}", x, y);
  // let book = give_thing(Book{year: 11});
  // cannot be executed

  compare_and_print("Listen up!", 9, 8);
}

At this code, we set T: Display and it means we can get any type T if T implemet std::fmt::Display(we imported std::fmt::Display, so we can omit std::fmt::).
So we can execute our code. As you can see at the comment of main function, Book struct type does not implement std::fmt::Display. So we cannot send Book struct type to give_thing function.

Also we can use two or more generics at once.

use std::fmt::Display;
use std::cmp::PartialOrd;

fn compare_and_print<
  T: Display, 
  U: Display + PartialOrd
  >(statement: T, num1: U, num2: U) {
  println!("{}! Is {} greater than {}? => {}", statement, num1, num2, num1 > num2);
}

fn main() {
  compare_and_print("Listen up!", 9, 8);
}

As we can see above, compare_and_print function has two Generics T, U. And U implements Display + PartialOrd.
First, let's see the logic of this function. we get statement, num1, num2 as param and print statement, num1, num2, num1>num2. So statement and num1, num2 have to implement Display. Also, num1, num2 have to implement PartialOrd, cause PartialOrd is for comparing things(and in the function, we are comparing num1, num2).
We can use multiple Generics with different implements like this.

Using Generics, we can make a lot more features with Rust!

profile
Surfer surfing on the dynamic flow of the world

0개의 댓글