본문 바로가기
Rust

[Rust] Generic 예제 (22일차)

by 꾸압 2023. 1. 4.

 

<예제 코드_1>

// A concrete type 'A'
struct A;

// In defining the type 'Single', the first use of 'A' is not preceded by '<A>'
// Therefore, 'Single' is a concrete type, and 'A' is definded as above.
struct Single(A);
//            ^ Here is 'Single's first use of the type 'A'.

// Here, '<T>' precedes the first use of 't', so 'SingleGen' is a generic type.
// Because the type parameter 'T' is generic, it could be anything, including
// the concerete type 'A' defined at the top.
struct SingleGen<T>(T);

fn main() {
    // 'Single' is concrete and explicitly takes 'A'.
    let _s = Single(A);

    // Create a variable '_char' of type 'SingleGen<char>'
    // and give it the value 'SingleGen('a)'.
    // Here, 'SingleGen' has a type parameter explicitly specified.
    let _char: SingleGen<char> = SingleGen('a');

    // 'SingleGen' can also have a type parameter implicitly specified:
    let _t      = SingleGen(A); // Uses 'A' defined at the top.
    let _i32    = SingleGen(6); // Uses 'i32'.
    let _char   = SingleGen('a');   // Uses 'char'.
}

 


 

<예제 코드_2>

fn largest(list: &[i32]) -> i32 {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];

    let result = largest(&numbers);
    println!("The largest number is {}", result);
   assert_eq!(result, 100);

    let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let result = largest(&numbers);
    println!("The largest number is {}", result);
   assert_eq!(result, 6000);
}

 


 

<참조 1> https://doc.rust-lang.org/rust-by-example/generics.html

 

 

'Rust' 카테고리의 다른 글

[Rust] Trait 예제 (24일차)  (0) 2023.01.06
[Rust] Generic : Data Type 예제 (23일차)  (0) 2023.01.05
[Rust] Enum 예제 (21일차)  (0) 2023.01.02
[Rust] Guess 예제 (20일차)  (0) 2023.01.01

댓글