본문 바로가기

Rust

Rust 함수

728x90

https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html

 

Variables and Mutability - The Rust Programming Language

As mentioned in the “Storing Values with Variables” section, by default, variables are immutable. This is one of many nudges Rust gives you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers. However, y

doc.rust-lang.org

Rust 함수는 다음과 같이 구성된다.

fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {x}");
}

 

fn으로 시작하고 파라미터 설정하는 방법은 여타 함수와 다르지 않다. 그러나 리턴값을 설정하고 반환하는 방식이 독특하다.

fn main() {
    let x = plus_one(5);

    println!("The value of x is: {x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

 

위와 같이 반환값은 인자 뒤에 -> i32와 같은 형식으로 반환 타입을 정해준다. 그리고 따로 return과 같은 형식으로 반환값을 명시적으로 알려주지 않아도 되고 묵시적으로 마지막 줄에 반환값을 적는다.

중간에 값을 반환하려면 마찬가지로 return 문을 활용하면 된다.

주의해야할 점은 반환값의 마지막에는 세미콜론을 붙이지 않는다. 

728x90

'Rust' 카테고리의 다른 글

Rust 제어문  (1) 2024.07.20
Rust 데이터 타입  (1) 2024.07.14
Rust 변수와 상수  (0) 2024.07.11
Rust 기초  (0) 2024.07.11