Menu
CoddyTech

暗黙的インターフェース

Coddyの「Rust開発者のためのDart」コースのレッスン 34/48。

Rustのトレイトは要件を明示的に宣言し、impl Trait for Typeによって適合性を確立します。トレイトが対応している場合、dyn Traitへの参照は動的ディスパッチを可能にします。Dartの通常のクラスは暗黙のインターフェースを作成し、implementsによって実装本体を継承せずに適合性を確立します。メソッド名が一致するだけでは、どちらの名目的な契約も確立されません。

Dartの通常のクラスはすべて、そのインスタンスメンバーから暗黙のインターフェースを定義します。プライベートメンバーはそのインターフェースの一部ですが、そのライブラリ内でのみ参照できます。implementsは実装本体を継承せずに、名目的な契約を確立します。

Rustの完全なプログラム:

trait Sound { fn sound(&self) -> &'static str; }
struct Bell;
impl Sound for Bell { fn sound(&self) -> &'static str { "ding" } }
fn main() { let bell = Bell; let s: &dyn Sound = &bell; println!("{}", s.sound()); }

Dartの完全なプログラム:

abstract class Sound{String sound();}
class Bell implements Sound{String sound()=>'ding';}
void main(){Sound s=Bell();print(s.sound());}
challenge icon

チャレンジ

簡単

抽象クラス Scorer を実装し、int score(String text) を定義してください。LengthScore implements Scorer はASCII文字列の長さを返します。VowelScore implements Scorer は小文字の a、e、i、o、u のみを数えます。functions.dart の best(List<String> words,Scorer scorer) は、スコアが最も高い最初の単語を返します。単語が空の場合は null を返します。入力は length または vowels で始まり、その後にASCIIの単語が続きます。最良の単語、または none を出力してください。

編集可能なファイルから出力しないでください。提供された exercise.dart が入力を解析して出力を返します。編集不可のドライバーは公開APIを個別に検証し、結果を改行1つとともに出力します。

コードは Scorer.dart、LengthScore.dart、VowelScore.dart、functions.dart、exercise.dart に記述してください。main.dart には提供された入出力コードが含まれており、編集できません。

自分で試してみよう

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Scorer.dart';
import 'LengthScore.dart';
import 'VowelScore.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(LengthScore().score('abc')==3 && VowelScore().score('area')==3);check(best(['x','aaa'],LengthScore())=='aaa');
stdout.writeln(solve(input));
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Rust開発者のためのDartのすべてのレッスン

自分で練習してみよう: Dartオンラインコンパイラ