100 Exercises To Learn Rust - 2.2 Variables 풀기

/// Given the start and end points of a journey, and the time it took to complete it,
/// calculate the average speed.
pub fn speed(start: u32, end: u32, time_elapsed: u32) -> u32 {
    //TODO: `distance`라는 이름의 변수를 정의하고, 테스트를 통과할 수 있도록 올바른 값을 지정하기
    //`distance` 변수의 타입을 명시해야 할 필요가 있을까요? 그렇다면 이유는 무엇일까요?
    // Don't change the line below
    distance / time_elapsed
}

 

distance 변수는 현재 정의되지 않은 채 사용되고 있으므로 먼저 distance 변수를 정의해주어야 한다.

 

test 모듈의 내용은 다음과 같다.

#[test]
    fn case1() {
        assert_eq!(speed(0, 10, 10), 1);
    }

    #[test]
    fn case2() {
        assert_eq!(speed(10, 30, 10), 2);
    }

    #[test]
    fn case3() {
        assert_eq!(speed(10, 31, 10), 2);
    }

 

distance는 시작지점부터 종료지점까지의 거리를 의미하므로 end - start라는 값을 가지면 된다.

이때 타입을 명시해야 할까?그렇지 않아도 된다.

 

러스트는 타입을 추론할 수 있다. distance의 값은 end와 start라는 두 u32 타입 변수에 의해 정해지므로, distance 변수 역시 u32 값일 것이라고 자연스럽게 생각할 수 있다. 러스트 언어도 이를 추론하도록 설계되었기 때문에, 타입을 명시하지 않아도 컴파일이 가능하다.

 

정답:

pub fn speed(start: u32, end: u32, time_elapsed: u32) -> u32 {
    // TODO: define a variable named `distance` with the right value to get tests to pass
    //  Do you need to annotate the type of `distance`? Why or why not?
    let distance = end - start;
    // Don't change the line below
    distance / time_elapsed
}