Rust 트레잇

mohadang·2023년 8월 20일
0

Rust

목록 보기
29/30
post-thumbnail

확장 메서드

Rust의 트레잇은 인터페이스나 추상 클래스와 비교되어 설명되곤 한다. 트레잇을 사용할 경우 인터페이스 처럼 구현을 강제 하지만 확장 메서드와 같은 기능도 가지고 있다.

C#의 확장 메서드

트레잇은 내가 만든 구조체 뿐만 아니라 다른 개발자가 만든 구조체 또는 데이터 타입에 사용 가능 하다.

trait Point {
    fn x(&self) -> f32;
    fn y(&self) -> f32;
}

impl Point for [f32; 2] {
    fn x(&self) -> f32 { self[0] }
    fn y(&self) -> f32 { self[1] }
}

fn main() {
    let p = [1.0, 2.0];
    println!("x: {}, y: {}", p.x(), p.y());
}

제네릭

C#의 인터페이스나 C++의 경우 템플릿 특수화 같이 트레잇에도 제네릭을 사용할 수 있다.

struct TwoGenerics;

trait Foo<T> {
    fn some_method(&self, input: T);
}

impl Foo<i32> for TwoGenerics {
    fn some_method(&self, input: i32) {}
}
impl Foo<String> for TwoGenerics {
    fn some_method(&self, input: String) {}
}

fn main() {
    let two_generics = TwoGenerics;
    two_generics.some_method(1);
    two_generics.some_method("hello".to_string());
}
#include<iostream>
using namespace std;
template <typename T>
T max(T a, T b) {
   return (a > b ? a : b);
}

template<>
double max(double a, double b) { // double 타입에 대해서는 이 메서드 사용.
   cout << a << " " << b << "중 큰수는 ? " <<endl;
   return (a > b ? a : b);
}

int main() 
  cout << max(5, 6) << endl;
  cout << max(12.5, 16.7) << endl;

  return 0;
}

트레잇의 제네릭에는 조건을 걸 수 있다.

impl<T> Clone for Vec<T> where T: Clone {...}

트레잇 타입 추론

트레잇을 사용하면 타입을 추론하여 일치하는 메서드를 알아서 호출해준다. 대표적인 예가 Default::default() 이다.

use std::collections::HashMap;

fn main() {
    let h: HashMap<usize, usize> = Default::default();
    let s: String = Default::default();
    println!("h: {:?}, s: {:?}", h, s);
}

HashMap에 대한 Default::default()를 보면 HashMap에 Default 트레잇이 구현되어 있다.

#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V, S> Default for HashMap<K, V, S>
where
    S: Default,
{
    /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
    #[inline]
    fn default() -> HashMap<K, V, S> {
        HashMap::with_hasher(Default::default())
    }
}

타입의 변환에 따라 로직이 변환된다.

let h: HashMap<usize, usize> // 타입
    = Default::default(); // 로직

Rust의 트레잇이란 ?

trait의 사전 의미는 특성이다. 말 그대로 특성을 부여하는 의미라고 생각된다. 인터페이스나 추상 클래스가 클래스에 어떤 구현 의무를 부여한다면 트레잇은 클래스 뿐만 아니라 데이터 타입에 특성을 부여하는 것이다.

참고

https://stackoverflow.com/questions/69477460/is-rust-trait-the-same-as-java-interface

profile
mohadang

0개의 댓글