Classes in Rust

jimmco
2 min readMar 15, 2016

--

Let’s start with a statement there are no classes in Rust. But don’t worry, we can still easily simulate classes behavior in Rust.

There is a minimal class example in Java

// Java
// class definition
class Dog {
public void bark() {
System.out.println("baf!");
}
}
// usage
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.bark();
}
}

In Rust, we don’t have class keyword but we have struct and impl so we can mix them to do this:

// Rust
// struct + impl = "class"
struct Dog;
impl Dog {
fn bark(&self) {
println!(“baf!”);
}
}
// execute
fn main() {
let d = Dog;
d.bark();
}

Now let’s assume we want to have some type of inheritance. Animal will parent class of Dog and will provide general method eat(). In Java it would look like this.

// Java
class Animal {
public void eat() {
System.out.println("eating");
}
}

class Dog extends Animal {
public void bark() {
System.out.println("baf!");
}
}

public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}

In Rust, we have to do it a little bit more explicitly. One possible way is to add Animal struct as a parent into Dog structure and call parent method from the particular method of Dog struct.

// Rust
struct Animal;
struct Dog {
parent: Animal,
}
impl Animal {
fn eat(&self) {
println!(“eating”);
}
}
impl Dog {
fn bark(&self) {
println!(“baf!”);
}
fn eat(&self) {
self.parent.eat();
}
}
fn main() {
let d = Dog { parent: Animal };
d.eat();
d.bark();
}

Or we can just call parent’s method directly.

// Rust
struct Animal;
struct Dog {
parent: Animal,
}
impl Animal {
fn eat(&self) {
println!(“eating”);
}
}
impl Dog {
fn bark(&self) {
println!(“baf!”);
}
}
fn main() {
let d = Dog { parent: Animal };
d.parent.eat();
d.bark();
}

Both examples are quite equal. First requires some more work but usage is cleaner.

And the expected output is this:

Running “cargo run”:
...
eating
baf!

--

--