구성된 객체
Coddy의 Rust 개발자를 위한 GDScript 코스 레슨. 48개 중 29번째.
소유하는 Rust 구조체 필드는 일반적으로 협력 객체를 소유하며, Rc 복제본은 이를 명시적으로 공유합니다. 이 단일 스레드 예제에서 RefCell은 검사된 내부 변경을 허용합니다. GDScript 객체 필드는 협력 객체를 복제하지 않고 자연스럽게 참조를 유지합니다. Rc와 RefCounted의 강한 참조 순환은 모두 메모리 누수를 일으킬 수 있으므로, 소유권 방향이나 약한 링크를 사용하세요. 생성 시 전달된 의존성을 다른 것으로 대체하지 않고 유지해야 합니다.
완전한 Rust 2021 프로그램입니다. 나열된 동일 디렉터리의 모듈과 함께 main.rs를 컴파일하세요.
Rust 파일 note.rs:
pub struct Note { pub text:String }
Rust 파일 envelope.rs:
use std::{rc::Rc,cell::RefCell};
use crate::note::Note;
pub struct Envelope { pub note:Rc<RefCell<Note>> }
Rust 파일 main.rs:
mod note; mod envelope;
use std::{rc::Rc,cell::RefCell};
fn main() { let n=Rc::new(RefCell::new(note::Note{text:"a".into()})); let e=envelope::Envelope{note:Rc::clone(&n)}; n.borrow_mut().text="b".into(); println!("{}",e.note.borrow().text); }
Rust 출력:
bGDScript 예제 파일 demo_note.gd:
class_name DemoNote
extends RefCounted
var text: String = "a"GDScript 예제 파일 demo_envelope.gd:
class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
note = valueGDScript 예제 파일 main.gd:
extends Node
func _ready() -> void:
var note: DemoNote = DemoNote.new()
var envelope: DemoEnvelope = DemoEnvelope.new(note)
note.text = "b"
print(envelope.note.text)GDScript 출력:
b챌린지
쉬움RateRule(cents:int)를 구현하고 cost(units:int)를 작성하세요. BillBox(rule:RateRule)는 전달된 rule을 저장하며 total(units:int)은 이를 위임 호출합니다. 이후 rule.cents를 변경하면 청구 금액에 반영되어야 합니다. Solve는 [rate,units]를 사용합니다.
입력은 stdin으로 전달되는 하나의 JSON 배열입니다. 잠긴 main은 이를 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 앞에 result=를 붙여 출력하고 줄바꿈합니다. 어떤 도우미 함수도 출력하면 안 됩니다. 입력 사례를 처리하기 전에 독립된 고정 테스트로 필수 API 동작을 확인하지만, 구현 방식은 강제하지 않습니다.
코드는 rate_rule.gd, bill_box.gd, exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 형식은 이름이 지정된 파일에 두세요.
직접 해보기
extends Node
func contract_ok(data: Array) -> bool:
var rule: RateRule = RateRule.new(2)
var bill: BillBox = BillBox.new(rule)
rule.cents = 7
if rule.cost(3) != 21 or bill.total(3) != 21: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Rust 개발자를 위한 GDScript의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러