Advertisement
Guest User

Untitled

a guest
Aug 17th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. public class JavaFoo {
  2. private static final String DATA = "Java";
  3. private final Bar bar;
  4.  
  5. public JavaFoo(Bar aBar) { this.bar = aBar;}
  6.  
  7. public void doSomething() { System.out.println("Woohoo! " + bar.toString()); }
  8.  
  9. public static void doSomethingStatic() { System.out.println(DATA); }
  10. }
  11.  
  12. --------------------------------------
  13. mod rust {
  14.  
  15. // Not "pub" so effectively private.
  16. const DATA: String = "Rust!";
  17.  
  18. pub struct RustFoo {
  19. bar: Bar // Can be immutable ("final") so long as we expose an immutable API
  20. }
  21.  
  22. impl RustFoo {
  23. // Common idiom to provide a new method to wrap ctor
  24. pub fn new(a_bar: Bar) -> RustFoo {
  25. // Here is the actual struct ctor call
  26. RustFoo{ bar: a_bar }
  27. }
  28.  
  29. // Instance methods must take either &self or &mut self
  30. pub fn do_something(&self) {
  31. println!("Woohoo! {:?}", bar);
  32. }
  33.  
  34. // "Java-static" functions (that is, functions belonging to the type but not taking an instance) do not take &self or &mut self.
  35. pub fn do_something_static() {
  36. println!("{}", DATA);
  37. }
  38.  
  39. // Note: If you think about it, the new() method we defined above is effectively a "Java static" function. In Rust, constructors are
  40. // already defined for you, so it's good to write wrappers around them. That is, in Rust, the idiom is to do something like:
  41. // public class Foo {
  42. // ... data ...
  43. // private Foo(...) already defined by compiler
  44. // public static Foo new(... args ...) {
  45. // return new Foo(... pass the args ...);
  46. // }
  47. // }
  48.  
  49. } // end of impl RustFoo
  50.  
  51. } // end of mod rust
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement