Answer#
Java and Rust agree on much of the vocabulary (interfaces and traits, generics, lambdas and closures, pattern-like instanceof), and they differ on the memory model. Java has a garbage collector, references everywhere and null; Rust has owned values, explicit borrows and no null. Most of a port is therefore a change of how data is owned and passed, while the control flow carries over.
| Java | Rust |
|---|---|
class with fields and methods | struct plus an impl block |
interface | trait; use Box<dyn Trait> where a variable has an interface type |
extends | composition, trait default methods, or an enum (see the thread on classes and inheritance) |
null, Optional<T> | Option<T> |
checked exception, throws | Result<T, E> (see the thread on Java exceptions) |
List<T>, ArrayList | Vec<T> |
Map<K, V>, HashMap | HashMap<K, V>, or BTreeMap<K, V> for sorted keys |
String, StringBuilder | &str and String |
stream().filter().map().sum() | iter().filter().map().sum() |
lambda (a -> a * 2) | a closure (arguments between vertical bars, as in the iterator example below) |
enum with fields and methods | enum with data, and an impl block |
record | struct with #[derive(Debug, Clone, PartialEq)] |
synchronized, ReentrantLock | Mutex<T> |
package, import | mod, use |
| Maven or Gradle dependency | a line in Cargo.toml |
| JUnit test | #[test] function, run by cargo test |
The Java program below has an interface implemented by a lambda, a lookup that throws a checked exception, a stream and an Optional. It was compiled and run with OpenJDK 17.0.18:
import java.util.*;
public class Javamap {
interface Greeter { String greet(String name); }
static class NotFound extends Exception { NotFound(String n) { super(n); } }
static int findAge(Map<String, Integer> ages, String name) throws NotFound {
Integer a = ages.get(name);
if (a == null) throw new NotFound(name);
return a;
}
public static void main(String[] args) throws Exception {
Greeter g = n -> "Good day, " + n + ".";
System.out.println(g.greet("Ada"));
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36); ages.put("Bo", 20);
System.out.println(findAge(ages, "Ada"));
try { findAge(ages, "Cy"); } catch (NotFound e) { System.out.println("not found: " + e.getMessage()); }
System.out.println(ages.values().stream().filter(a -> a > 21).mapToInt(a -> a).sum());
System.out.println(Optional.ofNullable(ages.get("Cy")).map(String::valueOf).orElse("unknown"));
}
}Good day, Ada.
36
not found: Cy
36
unknownThe same program in Rust, compiled and run with rustc 1.93.0:
use std::collections::HashMap;
trait Greeter {
fn greet(&self, name: &str) -> String;
}
struct Polite;
impl Greeter for Polite {
fn greet(&self, name: &str) -> String {
format!("Good day, {name}.")
}
}
#[derive(Debug)]
enum LookupError {
NotFound(String),
}
fn find_age(ages: &HashMap<String, u32>, name: &str) -> Result<u32, LookupError> {
ages.get(name).copied().ok_or_else(|| LookupError::NotFound(name.to_string()))
}
fn main() {
let g: Box<dyn Greeter> = Box::new(Polite);
println!("{}", g.greet("Ada"));
let ages: HashMap<String, u32> = [("Ada".to_string(), 36), ("Bo".to_string(), 20)].into_iter().collect();
println!("{:?}", find_age(&ages, "Ada"));
println!("{:?}", find_age(&ages, "Cy"));
// Java: ages.values().stream().filter(a -> a > 21).mapToInt(a -> a).sum()
println!("{}", ages.values().filter(|&&a| a > 21).sum::<u32>());
// Java Optional<String>.map(...).orElse(...)
println!("{}", ages.get("Cy").map(|a| a.to_string()).unwrap_or_else(|| "unknown".to_string()));
}Good day, Ada.
Ok(36)
Err(NotFound("Cy"))
36
unknownWhat changed besides the syntax: the lookup's possible failure is in its return type; the lambda that implemented Greeter became a named type (a closure can also implement a trait through a Fn bound); and no Integer boxing exists, since u32 is a plain value.
How to do it#
- Port the data classes first: fields become struct fields; decide for each whether the struct owns the data (
String,Vec<T>) or borrows it (&str,&[T], which needs a lifetime). Owning is the easy start. - Port the interfaces to traits and the implementing classes to structs with
impl Trait for Struct. - Port the methods.
thisbecomes&self(read),&mut self(change) orself(consume). - Replace exceptions with
Resultand null withOption, starting from the leaf methods. - Replace shared mutable state (static fields, singletons, listeners) as the threads on globals and callbacks describe.
- Port tests last, or better first (see the thread on golden files).
Common mistakes#
- Using
Rc<RefCell<T>>for every object reference to copy Java's "everything is a reference". Start with owned values and borrows, and add sharing only where the design needs it. - Porting inheritance trees literally. Look at what the hierarchy was used for.
- Expecting
HashMapiteration order to match Java's. Neither promises an order; sort or useBTreeMapwhen order matters (see the thread on key order).
Related questions#
What happens to Java's equals and hashCode?#
Derive PartialEq, Eq and Hash with #[derive(...)]. The derived versions compare all fields.
How do I call my existing Java library from Rust, or the other way?#
Through JNI or the Java foreign function API, using the C-compatible layer. This thread did not run that path.
Sources#
- The Rust Book: https://doc.rust-lang.org/book/
std::collections::HashMap: https://doc.rust-lang.org/std/collections/struct.HashMap.html