티스토리 뷰

Rust-Language

method

kmj24 2021. 4. 7. 23:09

method

 - 함수와 유사하게 fn키워드로 선언되고, parameter, return값이 있으며, 호출이 가능하다.

 - 함수와 다른점은 구조체의 내용안에 정의되며(열거형, trait객체안에도 정의 가능), 첫번째 parameter는 항상 self이다

 - selft는 해당 method가 호출되고 있는 구조체의 인스턴스이다.

struct Rectangle{
    length : u32,
    width : u32
}

pub fn run(){
    let rect1 = Rectangle{
        length: 50,
        width : 30
    };
    println!("{}", rect1.area());
}

impl Rectangle{
    fn area(&self) -> u32{
        self.length * self.width
    }
}

Rectangle의 내용 안에 함수를 정의하기 위해, impl(implementation)블록으로 시작한다.(impl은 구조체와 동일한 이름으로 선언)

impl block내에 함수를 선언하며, parameter를 self로 변경

위의 코드에서 &self는 rect1을 의미한다.

여기서, 다음 아래의 코드는 동일한 의미이다.

rect1.area(); // 자동으로 해당 method의 시그니처와 맞도록 매칭함,
&rect1.area();
(&rect1).area();

 

파라미터를 가진 method

Rectangle의 인스턴스가 다른 Rectangle의 인스턴스를 가져와서 사용하는 방법

첫번째로 선언한 Rectangle 의 값이 클경우 true(rect1 > rect2), 두번째로 선언한 Rectagle의 값이 클경우(rect1 < rect3) false를 반환

struct Rectangle{
    length : u32,
    width : u32
}
pub fn run(){
    let rect1 = Rectangle{
        length: 50,
        width : 30
    };
    let rect2 = Rectangle{
        length: 10,
        width : 20
    };
    let rect3 = Rectangle{
        length: 50,
        width : 60
    };
    println!("{}", rect1.can_hlod(&rect2));
    println!("{}", rect1.can_hlod(&rect3));
}
impl Rectangle{
    fn can_hlod(&self, other : &Rectangle) -> bool{
        self.length > other.length && self.width > other.width
    }
}

또한, 아래의 코드와 같이 method에 parameter를 여러개 사용또한 가능하다.

#[derive(Debug)]
struct Rectangle{
    length : u32,
    width : u32
}

pub fn run(){
    let rect1 = Rectangle{
        length: 50,
        width : 30
    };
    let rect2 = Rectangle{
        length: 10,
        width : 20
    };
    let rect3 = Rectangle{
        length: 50,
        width : 60
    };
    rect1.multi_param(&rect2, &rect3);
}

impl Rectangle{

    fn multi_param(&self, other1 : &Rectangle, other2 : &Rectangle){
        println!("{:#?}, {:#?}, {:#?}", self, other1, other2);
    }
}

출력결과

 

연관함수, associated functions

impl block내에서 self parameter를 갖지 안흔 함수도 정의 가능하다.

이를 연관함수라고 한다.

연관함수는 method가 아니라 그냥 함수이다. 

연관함수는 주로 새로운 구조체의 인스턴스를 반환해주는 생성자로 자주 사용된다고 한다.

#[derive(Debug)]
struct Rectangle{
    length : u32,
    width : u32
}

pub fn run(){
    let sq = Rectangle::square(3);
    println!("{:#?}", sq);
}

impl Rectangle{
    fn square(size: u32) -> Rectangle {
        Rectangle { length: size, width: size }
    }
}

연관함수 호출 방법은 구조체의 이름과 ::와 연관함수명을 이용하여 위의 코드와 같이 선언한다.

:: 문법은 연관함수와 module에 생성된 이름공간 두 곳 모두에서 사용된다.

 

 

이 장의 전체 코드

#[derive(Debug)]
struct Rectangle{
    length : u32,
    width : u32
}

pub fn run(){
    let rect1 = Rectangle{
        length: 50,
        width : 30
    };
    let rect2 = Rectangle{
        length: 10,
        width : 20
    };
    let rect3 = Rectangle{
        length: 50,
        width : 60
    };
    println!("{}", rect1.area());
    println!("{}", rect1.can_hlod(&rect2));
    println!("{}", rect1.can_hlod(&rect3));
    rect1.multi_param(&rect2, &rect3);
    let sq = Rectangle::square(3);
    println!("{:#?}", sq);
}

impl Rectangle{
    fn area(&self) -> u32{
        self.length * self.width
    }
    fn can_hlod(&self, other : &Rectangle) -> bool{
        self.length > other.length && self.width > other.width
    }
    fn multi_param(&self, other1 : &Rectangle, other2 : &Rectangle){
        println!("{:#?}, {:#?}, {:#?}", self, other1, other2);
    }
    fn square(size: u32) -> Rectangle {
        Rectangle { length: size, width: size }
    }
}

 

 

참고 : rinthel.github.io/rust-lang-book-ko/ch05-03-method-syntax.html

 

메소드 문법 - The Rust Programming Language

메소드(method) 는 함수와 유사합니다: 이들은 fn 키워드와 이름을 가지고 선언되고, 파라미터와 반환값을 가지고 있으며, 다른 어딘가로부터 호출되었을때 실행될 어떤 코드를 담고 있습니다. 하

rinthel.github.io

'Rust-Language' 카테고리의 다른 글

match 흐름 제어 연산자  (0) 2021.04.09
열거형  (0) 2021.04.09
구조체  (0) 2021.04.07
Slices  (0) 2021.04.05
참조자와 빌림  (0) 2021.04.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함