Menu
Coddy logo textTech

요약 - 좌표 지점

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 28번째.

challenge icon

챌린지

쉬움

모든 숫자 유형에서 작동하는 유연한 좌표 시스템을 만들어 봅시다! 하나의 정의만으로 격자 기반 게임에서는 정수를, 정밀한 그래픽에서는 부동 소수점 숫자를 사용해 위치를 나타낼 수 있는 generic Point struct를 만듭니다.

코드를 두 파일로 구성합니다:

  • point.rs: 두 개의 public fields인 xy를 가진 public generic Point<T> struct를 Define합니다. 두 fields의 유형은 모두 T입니다. point를 위한 methods를 Implement합니다:
    • new associated function: x 및 y 좌표로 point를 생성합니다.
    • translate method: dx 및 dy 값을 받아 해당 양만큼 좌표가 이동된 새로운 Point를 returns합니다. 이를 위해서는 T가 addition 및 copying을 support해야 하므로 bound T: std::ops::Add<Output = T> + Copy를 사용합니다.
  • main.rs: point module을 가져오고 동일한 generic struct가 서로 다른 숫자 유형에서 원활하게 작동하는 방식을 보여 줍니다.

main file에서 generic Point를 다음과 같이 보여 줍니다:

  1. 처음 두 inputs를 사용해 integer point를 Create합니다(i32로 parsed).
  2. 세 번째와 네 번째 inputs를 사용해 이를 Translate합니다(역시 i32).
  3. 다섯 번째와 여섯 번째 inputs를 사용해 floating-point point를 Create합니다(f64로 parsed).
  4. 세 point를 모두 표시합니다.

Output은 다음 format을 따라야 합니다:

Integer point: ({x}, {y})
After translation: ({x}, {y})
Float point: ({x}, {y})

예를 들어 inputs가 3, 5, 2, -1, 1.5, 2.5인 경우:

Integer point: (3, 5)
After translation: (5, 4)
Float point: (1.5, 2.5)

Point::new(3, 5)Point<i32>를 Create하는 반면 Point::new(1.5, 2.5)Point<f64>를 Create하는 방식을 확인하세요. 동일한 struct Define이 두 유형 모두에 맞게 조정됩니다!

여섯 개의 inputs를 받습니다. 첫 번째 point를 위한 두 개의 정수, translation을 위한 두 개의 정수, 두 번째 point를 위한 두 개의 부동 소수점 숫자입니다.

직접 해보기

mod point;

use point::Point;

fn main() {
    // 입력 읽기
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let x1: i32 = input.trim().parse().expect("Invalid input");
    
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let y1: i32 = input.trim().parse().expect("Invalid input");
    
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let dx: i32 = input.trim().parse().expect("Invalid input");
    
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let dy: i32 = input.trim().parse().expect("Invalid input");
    
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let x2: f64 = input.trim().parse().expect("Invalid input");
    
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let y2: f64 = input.trim().parse().expect("Invalid input");
    
    // TODO: Create an integer point using x1 and y1
    
    // TODO: Translate the integer point by dx and dy
    
    // TODO: x2와 y2를 사용하여 부동소수점 포인트 생성
    
    // TODO: 필요한 형식으로 결과 출력:
    // println!("Integer point: ({}, {})", ...);
    // println!("After translation: ({}, {})", ...);
    // println!("Float point: ({}, {})", ...);
}

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러