CodeBlanks Logo Icon CodeBlanks

Generic method

Write an impl block and methods for a generic struct.

Generic methods

When writing methods for a generic type, the type parameter is also declared after impl. These methods hold for every T:

impl<T> Cift<T> {
    fn ilk(&self) -> &T {
        &self.a
    }
}

A method can also be written only for a specific concrete type; then impl has no parameter:

impl Cift<f64> {
    fn ortalama(&self) -> f64 {
        (self.a + self.b) / 2.0
    }
}

Conditional methods

A third option is to tie the method to a trait bound: the method exists only if T has a certain behaviour:

use std::fmt::Display;

impl<T: Display + PartialOrd> Cift<T> {
    fn buyugu_yaz(&self) {
        if self.a >= self.b {
            println!("büyük: {}", self.a);
        } else {
            println!("büyük: {}", self.b);
        }
    }
}

A separate generic parameter can also be declared at method level: fn karistir<U>(self, o: Cift<U>) -> Nokta<T, U>.

Practice Pair methods

For Cift<T>, write fn ilk(&self) -> &T working for every T, and fn ortalama(&self) -> f64 only for Cift<f64>. Print both results for Cift { a: 2.0, b: 5.0 } separated by a space.

Starter code

main.rs
struct Cift<T> {
    a: T,
    b: T,
}

fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Cift<T> {
    a: T,
    b: T,
}

impl<T> Cift<T> {
    fn ilk(&self) -> &T {
        &self.a
    }
}

impl Cift<f64> {
    fn ortalama(&self) -> f64 {
        (self.a + self.b) / 2.0
    }
}

fn main() {
    let c = Cift { a: 2.0, b: 5.0 };
    println!("{} {}", c.ilk(), c.ortalama());
}

Expected output

2 3.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Does <code>Cift { a: 1, b: 2 }.ortalama()</code> compile? (<code>ortalama</code> only for <code>Cift&lt;f64&gt;</code>)

  • Yes, it returns 1.5
  • Yes, it returns 1
  • Runtime error
  • No; ortalama isn't defined for Cift<i32> Correct answer

Explanation: An impl written for a concrete type is only visible on that type. Writing Cift { a: 1.0, b: 2.0 } works.

2 impl parameter

Question
impl____ Cift<T> {
    fn ilk(&self) -> &T {
        &self.a
    }
}
Answer
impl<T> Cift<T> {
    fn ilk(&self) -> &T {
        &self.a
    }
}

Explanation: For methods valid for every T, impl<T> is written.

3 impl form and scope

Term Meaning
impl<T> Cift<T> Every T
impl Cift<f64> Only f64
impl<T: Display> Cift<T> T with Display
fn f<U>(..) Method-specific type

All lessons in Intermediate