Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JavaFoo {
- private static final String DATA = "Java";
- private final Bar bar;
- public JavaFoo(Bar aBar) { this.bar = aBar;}
- public void doSomething() { System.out.println("Woohoo! " + bar.toString()); }
- public static void doSomethingStatic() { System.out.println(DATA); }
- }
- --------------------------------------
- mod rust {
- // Not "pub" so effectively private.
- const DATA: String = "Rust!";
- pub struct RustFoo {
- bar: Bar // Can be immutable ("final") so long as we expose an immutable API
- }
- impl RustFoo {
- // Common idiom to provide a new method to wrap ctor
- pub fn new(a_bar: Bar) -> RustFoo {
- // Here is the actual struct ctor call
- RustFoo{ bar: a_bar }
- }
- // Instance methods must take either &self or &mut self
- pub fn do_something(&self) {
- println!("Woohoo! {:?}", bar);
- }
- // "Java-static" functions (that is, functions belonging to the type but not taking an instance) do not take &self or &mut self.
- pub fn do_something_static() {
- println!("{}", DATA);
- }
- // Note: If you think about it, the new() method we defined above is effectively a "Java static" function. In Rust, constructors are
- // already defined for you, so it's good to write wrappers around them. That is, in Rust, the idiom is to do something like:
- // public class Foo {
- // ... data ...
- // private Foo(...) already defined by compiler
- // public static Foo new(... args ...) {
- // return new Foo(... pass the args ...);
- // }
- // }
- } // end of impl RustFoo
- } // end of mod rust
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement