Rust Libraries

You use rust_library to create a new Rust library for Android.

Here we declare a dependency on two libraries:

  • libgreeting, which we define below,
  • libtextwrap, which is a crate already vendored in external/rust/crates/.

hello_rust/Android.bp:

  1. rust_binary {
  2. name: "hello_rust_with_dep",
  3. crate_name: "hello_rust_with_dep",
  4. srcs: ["src/main.rs"],
  5. rustlibs: [
  6. "libgreetings",
  7. "libtextwrap",
  8. ],
  9. prefer_rlib: true, // Need this to avoid dynamic link error.
  10. }
  11. rust_library {
  12. name: "libgreetings",
  13. crate_name: "greetings",
  14. srcs: ["src/lib.rs"],
  15. }

hello_rust/src/main.rs:

  1. //! Rust demo.
  2. use greetings::greeting;
  3. use textwrap::fill;
  4. /// Prints a greeting to standard output.
  5. fn main() {
  6. println!("{}", fill(&greeting("Bob"), 24));
  7. }

hello_rust/src/lib.rs:

  1. //! Greeting library.
  2. /// Greet `name`.
  3. pub fn greeting(name: &str) -> String {
  4. format!("Hello {name}, it is very nice to meet you!")
  5. }

You build, push, and run the binary like before:

  1. m hello_rust_with_dep
  2. adb push "$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep" /data/local/tmp
  3. adb shell /data/local/tmp/hello_rust_with_dep
  1. Hello Bob, it is very
  2. nice to meet you!