조합과 소유권
Coddy의 C 개발자를 위한 Rust 코스 레슨. 48개 중 34번째.
컴포지션은 하나의 값 안에 다른 값을 저장합니다. 필드가 소유된 String 또는 Vec<T>라면 바깥 값이 해당 메모리 할당을 소유하며, 소유자가 드롭될 때 Rust가 이를 해제합니다. 바깥 구조체를 이동하면 해당 필드의 소유권도 이전됩니다. self를 받는 메서드는 복사하지 않고 소유된 필드를 반환할 수 있습니다. 아래 C의 봉투 구조체는 관례에 따라 할당된 메시지를 소유하며, 해당 포인터를 해제하기 전에 명시적으로 이전합니다. Rust의 봉투 구조체는 이동된 필드를 통해 같은 이전을 표현하며 수동으로 해제할 필요가 없습니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Message { char *text; };
struct Envelope { struct Message message; };
int main(void) {
struct Envelope e;
e.message.text = malloc(5);
if (!e.message.text) return 1;
strcpy(e.message.text, "note");
char *text = e.message.text;
e.message.text = NULL;
printf("%s\n", text);
free(text);
return 0;
}Rust
struct Message { text: String }
struct Envelope { message: Message }
impl Envelope { fn open(self) -> String { self.message.text } }
fn main() {
let e = Envelope { message: Message { text: "note".to_string() } };
let text = e.open();
println!("{}", text);
}C 포인터를 복사해도 메모리 할당이 복사되거나 누가 이를 해제할지 정해지는 것은 아닙니다. Rust String을 이동하면 소유권이 이전됩니다. 두 번째 메모리 할당이 필요한 경우에만 clone을 사용하세요.
챌린지
쉬움공개 필드 name: String과 minutes: i32를 가진 stop::Stop을 구현하세요. journey::Journey::new() -> Journey는 소유권을 가진 빈 컬렉션을 생성합니다. add(&mut self, stop: Stop)은 소유권을 가져와 도착 순서대로 추가합니다. total(&self) -> i32은 정류장을 제거하지 않고 분의 합계를 반환합니다. finish(self) -> Vec<Stop>은 여정을 소비하고 소유한 모든 정류장을 순서대로 반환합니다. solve는 완전한 name minutes 쌍을 읽습니다. 이름에는 공백이 없으며, 분은 0부터 1000 사이이고, 정류장은 최대 100개입니다. 첫 번째 줄에는 total:n을 반환하고, 두 번째 줄에는 쉼표로 구분된 정류장 이름을 반환하세요. 여정이 비어 있으면 empty를 사용하세요.
필수로 내보내야 하는 API를 구현하고, 마지막 개행 없이 exercise::solve(input: &str) -> String의 결과를 반환하세요. 편집 가능한 코드에서 출력하지 마세요. 수정할 수 없는 드라이버는 필수 API를 각각 검사하고, stdin 전체를 읽은 다음 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다.
코드는 exercise.rs, stop.rs, journey.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stop;
mod journey;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
let mut j = journey::Journey::new(); assert_eq!(j.total(), 0);
j.add(stop::Stop { name: "ridge".to_string(), minutes: 23 });
j.add(stop::Stop { name: "ridge".to_string(), minutes: 0 });
j.add(stop::Stop { name: "lake".to_string(), minutes: 8 });
assert_eq!(j.total(), 31); assert_eq!(j.total(), 31);
let out = j.finish(); assert_eq!(out.len(), 3);
assert_eq!((&out[0].name, out[0].minutes), (&"ridge".to_string(), 23));
assert_eq!((&out[1].name, out[1].minutes), (&"ridge".to_string(), 0));
assert_eq!((&out[2].name, out[2].minutes), (&"lake".to_string(), 8));
assert!(journey::Journey::new().finish().is_empty());
// PUBLIC API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러