본문 바로가기

Rust

Rust, Hello world

반응형

시작은 아래와 같이 hello world,, 로 시작한다. 

 

아래와 같이 hello.rs를 작성하고,  

rustc hello.rs 로 컴파일 하면 실행파일이 나오고 이를 실행시키면 된다.

 

fn main(){ 
  println!("Hello, World"); 
}

 

println!은 매크로이다, 마지막에 !가 붙는것은 매크로를 의미한다. 

rust 언어만의 독특한 점이다.   

 

이렇게 실행하는 것 말고도 cargo를 사용하는 방법이 있다. 

 

아래와 같이 cargo new를 이용해서 project를 생성하면, 아래와 같이 폴더가 만들어지고, 

cargo를 이용해서 build, run을 할 수가 있다. 

>cargo new --bin hello_rust
Compiling hello_rust v0.1.0 (\hello_rust)
    Finished dev [unoptimized + debuginfo] target(s) in 1.40s
     Running `target\debug\hello_rust.exe`
     
> cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
    
 > cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target\debug\hello_rust.exe`
Hello, world!

 

 

아래는 또 다른 함수를 한번 보자, gcd를 구하는 함수이다. 


fn gcd (mut n: u64, mut m:u64) -> u64 {
  assert!(n != 0 ; m != 0);
  while (m != 0) {
     if ( m < n ) {
       let t = m; 
       m = n;
       n = t;
     }
     m = m % n;
  }
  n 
}

 

rust 특징이, 정적언어의 진화판이다. 그래서 형(type)을 명시해 주어야 된다. 

type을 명시해 주어야 컴파일타임에 할수 있는건 다 할 수 있다. 

 

"->" 은 return type을 의미하는 것임이다. 

 

return 굳이 명시 하지 않아도 마지막 문장에서 표현된 expression이 return값이 되고, 

함수 중간에 return하는 경우만 return을 명시한다. 

 

#[test] 
fn test_gcd() {
  assert_eq!(gcd(14,15),1);
  assert_eq!(gcd(2*3*5*11*17,
                 3*7*11*13*19), 3*11);
                 
}

 

#[test]는 test function위 에 위치하고, 

normal compilation에서는 이 함수는 패스한다. 

 

 

반응형

'Rust' 카테고리의 다른 글

Rust, 튜플  (0) 2020.01.20
Rust, 자료형 Numeric(정수)  (0) 2020.01.14
Rust , VSCode 환경 설정  (0) 2019.12.30
Rust, Global constant (전역 상수)  (0) 2019.12.19
Rust, 장점, 설치 Install  (0) 2019.12.10