트레이트와 계약
Coddy의 PHP 개발자를 위한 Rust 코스 레슨. 48개 중 36번째.
PHP 인터페이스는 클래스가 명시적으로 구현하는 동작을 정의하며, PHP 트레이트는 별도의 코드 재사용 기능입니다. Rust 트레이트는 동작 계약이며 PHP 트레이트 조합과 직접적으로 같은 의미가 아닙니다. impl Label for Lamp는 필수 메서드를 제공합니다. 이름이 같은 고유 메서드만으로는 바운드를 충족하지 않습니다. 예제에서는 데이터 표현과 관계없이 레이블을 요청합니다. Rust 트레이트는 기본 구현을 제공할 수 있지만 상속된 인스턴스 필드나 공통 클래스 레이아웃을 추가하지는 않습니다. 여러 타입이 동일한 기능을 구현할 수 있으며, 호출자는 나중에 정적 디스패치나 동적 디스패치를 선택할 수 있습니다. 공유 저장소와 동작을 노출하는 계약은 분리해 두세요.
PHP: 완전한 프로그램
<?php
declare(strict_types=1);
interface Label { public function label(): string; }
final class Lamp implements Label {
public function label(): string { return "desk"; }
}
function show(Label $item): void { echo $item->label(), "\n"; }
show(new Lamp());
Rust: 완전한 프로그램
trait Label { fn label(&self) -> &'static str; }
struct Lamp;
impl Label for Lamp { fn label(&self) -> &'static str { "desk" } }
fn show<T: Label>(item: &T) { println!("{}", item.label()); }
fn main() { show(&Lamp); }PHP와 Rust에서 trait라는 단어를 기계적으로 같은 뜻으로 옮기지 마세요. 두 언어에서 그 역할은 서로 다릅니다.
챌린지
쉬움필수 cost(&self, units: i32) -> i32와 각 인수에 대해 cost를 호출하고 결과를 더하는 기본 메서드 pair(&self, first: i32, second: i32) -> i32를 포함하도록 charge::Charge를 정의하세요. 별도의 모듈에서 flat::Flat { pub fee: i32 }와 per_unit::PerUnit { pub rate: i32 }에 해당 트레이트를 구현하세요. 정액 요금은 단위 수가 0이면 0이고, 그렇지 않으면 요금입니다. 단위당 요금은 요율에 단위 수를 곱한 값입니다. 모든 단위 수, 요금 및 요율은 음수가 아닙니다. solve는 mode amount first second를 읽습니다. 여기서 mode는 flat 또는 unit이고, 세 정수는 각각 1000 이하입니다. 첫 번째 비용, 두 번째 비용, 두 비용의 합을 공백으로 구분해 반환하세요.
필수 내보내기 API를 구현하고, exercise::solve(input: &str) -> String의 결과를 마지막 줄바꿈 없이 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 수정할 수 없는 드라이버는 필수 API를 각각 확인하고, 표준 입력 전체를 읽은 다음 반환된 텍스트를 마지막에 줄바꿈 하나를 붙여 출력합니다.
코드는 exercise.rs, charge.rs, flat.rs, per_unit.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod charge;
mod flat;
mod per_unit;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
use charge::Charge;
let f = flat::Flat { fee: 19 }; let u = per_unit::PerUnit { rate: 7 };
assert_eq!(f.cost(0), 0); assert_eq!(f.cost(11), 19); assert_eq!(f.pair(0, 8), 19);
assert_eq!(u.cost(6), 42); assert_eq!(u.cost(0), 0); assert_eq!(u.pair(3, 8), 77);
struct CustomCharge;
impl charge::Charge for CustomCharge { fn cost(&self, units: i32) -> i32 { units * units + 2 } }
let custom = CustomCharge;
assert_eq!(custom.pair(3, 5), 38); assert_eq!(custom.pair(0, 0), 4);
assert_eq!(f.pair(2, 3), 38);
// PUBLIC API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러