必要條件
在本教學課程中,您將使用「建立 FIDL 程式庫」教學課程中的 fuchsia.examples FIDL 程式庫。這個 FIDL 程式庫的程式碼位於 //examples/fidl/fuchsia.examples。請花點時間查看程式碼,再繼續操作。
總覽
本教學課程將詳細說明如何透過 Rust 使用 FIDL,方法是建立單元測試,做為探索 Rust 繫結的「測試環境」。
本文說明如何完成下列工作:
範例程式碼位於 Fuchsia 簽出的 //examples/fidl/rust/fidl_crates/ 中。如果您想在學習本教學課程時自行編寫所有程式碼,可以移除範例程式碼:
rm -r examples/fidl/rust/fidl_crates/*
編寫「Hello World」程式
將 main 函式新增至
examples/fidl/rust/fidl_crates/src/main.rs:fn main() { println!("Hello, world!"); }定義
rustc_binary,然後透過$host_toolchain建立測試的依附元件,這會建構主機的二進位檔。如要這麼做,請在examples/fidl/rust/fidl_crates/BUILD.gn中加入以下內容:import("//build/rust/rustc_binary.gni") rustc_binary("fidl_crates_bin") { edition = "2024" sources = [ "src/main.rs" ] } group("fidl_crates") { testonly = true deps = [ ":fidl_crates_bin($host_toolchain)" ] }在建構作業中加入範例
fx set core.x64 --with //examples/fidl/rust/fidl_crates建構範例
fx build執行二進位檔
out/default/host_x64/fidl_crates_bin您應該會看到「Hello World」訊息。
將 Rust FIDL 繫結新增為依附元件
對於每個 FIDL 程式庫宣告 (包括「編譯 FIDL」中的宣告),系統會在原始目標名稱下產生包含該程式庫 Rust 繫結程式碼的 FIDL crate,並附加 _rust。
請參照這個產生的 Crate,新增 Rust 繫結的依附元件。新的 rustc_binary 目標應如下所示:
rustc_binary("fidl_crates_bin") {
edition = "2024"
deps = [ "//examples/fidl/fuchsia.examples:fuchsia.examples_rust" ]
sources = [ "src/main.rs" ]
}
(選用) 如要查看新產生的繫結,請按照下列步驟操作:
- 使用
fx build重新建構。 - 切換至生成的檔案目錄:
out/default/fidling/gen/examples/fidl/fuchsia.examples/fuchsia.examples。產生的程式碼位於fidl_fuchsia_examples.rs。如果您設定了不同的建構輸出目錄,可能需要變更out/default。您可以使用cat .fx-build-dir查看建構輸出目錄。
如要進一步瞭解如何尋找產生的繫結程式碼,請參閱「查看產生的繫結程式碼」。
在專案中使用 FIDL Rust crate
新增測試模組和預留位置測試,建立一個可以試用產生的 FIDL crate 的地方:
#[cfg(test)]
mod test {
#[test]
fn fidl_crates_usage() {
}
}
接著,您需要設定 with_unit_tests 引數,透過測試進行建構:
rustc_binary("fidl_crates_bin") {
edition = "2024"
test_deps = [ "//examples/fidl/fuchsia.examples:fuchsia.examples_rust" ]
with_unit_tests = true
sources = [ "src/main.rs" ]
}
這會產生 fidl_crates_bin_test 目標,接著應新增至建構群組:
group("fidl_crates") {
testonly = true
deps = [
":fidl_crates_bin($host_toolchain)",
":fidl_crates_bin_test($host_toolchain)",
]
}
如要匯入 Crate,請在 tests 模組頂端加入以下內容。在 Fuchsia 樹狀結構中,FIDL crate 通常會使用較短的別名,以求簡潔:
use fidl_fuchsia_examples as fex;
使用產生的繫結程式碼
現在,您可以使用產生的繫結程式碼編寫一些程式碼。如要進一步瞭解繫結,請參閱「Rust 繫結參考資料」。
如要開始使用,您也可以使用下方的程式碼範例。您可以在 fidl_crates_usage 測試中加入以下內容:
let flags = fex::FileMode::READ | fex::FileMode::WRITE;
println!("{:?}", flags);
let from_raw = fex::LocationType::from_primitive(1).expect("Could not create LocationType");
assert_eq!(from_raw, fex::LocationType::Museum);
assert_eq!(fex::LocationType::Restaurant.into_primitive(), 3);
let red = fex::Color { id: 0u32, name: "red".to_string() };
println!("{:?}", red);
let int_val = fex::JsonValue::IntValue(1);
let str_val = fex::JsonValue::StringValue("1".to_string());
println!("{:?}", int_val);
assert_ne!(int_val, str_val);
let user = fex::User { age: Some(20), ..Default::default() };
println!("{:?}", user);
assert!(user.age.is_some());
如要重新建構及執行測試,請執行:
fx test -vo fidl_crates_bin_test