What is a Function in Rust?
Basic Function Syntax
Creating an Object in Rust (Using struct)
How to Call Function Using an Object (Method Call)
Different Ways to Create an Object in Rust
Function That Modifies Object (&mut self)
Calling Function Without Object (Normal Function)
Function Types Summary Table
Different ways to create objects and call functions in rust and java
Java Full Code (One File) for object creation and function calling
Rust Full Code (One File) for object creation and function calling
What is a Function in Rust?
A function in Rust is a reusable block of code that:
Performs a specific task
Can take parameters
Can return a value
Basic Function Syntax
fn function_name(parameter: Type) -> ReturnType {
// logic
}
Example: Simple Function
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let result = add(10, 20);
println!("Sum = {}", result);
}
2️⃣
Creating an Object in Rust (Using struct)
Rust does not have classes, but it uses structs to create objects.
Rust: Basic Struct (Object Blueprint)
struct Person {
name: String,
age: u32,
}
Java: Basic Class (Object Blueprint)
class Person {
String name;
int age;
}
Object Creation Example
Java
Person p = new Person();
p.name = "Ashwani";
p.age = 30;
Rust
let p = Person {
name: "Ashwani".to_string(),
age: 30,
};
How to Call Function Using an Object (Method Call)
Functions related to a struct are written using impl.
Method Using Object (&self)
struct Person {
name: String,
age: u32,
}
impl Person {
fn display(&self) {
println!("Name: {}, Age: {}", self.name, self.age);
}
}
fn main() {
let p1 = Person {
name: String::from("Ashwani"),
age: 30,
};
p1.display(); // calling function using object
}
Java Equivalent (Method Using Object)
class Person {
String name;
int age;
// Method using object (similar to &self)
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Object creation
Person p1 = new Person();
p1.name = "Ashwani";
p1.age = 30;
// Calling method using object
p1.display();
}
}
✔ &self means the function borrows the object (read-only).
4️⃣
Different Ways to Create an Object in Rust
✅ Way 1: Direct Struct Initialization
Rust
let p1 = Person {
name: String::from("Amit"),
age: 25,
};
java
Person p1 = new Person("Amit", 25);
Common Java Class (Used in All Examples)
class Person {
String name;
int age;
// Way 2: Constructor (like Rust new())
Person(String name, int age) {
this.name = name;
this.age = age;
}
// Way 4: Static method (like associated function)
static Person defaultPerson() {
return new Person("Unknown", 0);
}
}
✅ Way 2: Using a Constructor Function (new)
impl Person {
fn new(name: String, age: u32) -> Person {
Person { name, age }
}
}
fn main() {
let p2 = Person::new(String::from("Ravi"), 28);
}
java (Parameterized Constructor)
Person p2 = new Person("Ravi", 28);
✔ Most professional Rust code uses this style
✅ Way 3: Mutable Object
let mut p3 = Person {
name: String::from("Neha"),
age: 22,
};
p3.age = 23;
Java (Objects Are Mutable by Default)
Person p3 = new Person("Neha", 22);
p3.age = 23; // allowed without extra keywords
✅ Way 4: Associated Function (Static Method)
impl Person {
fn default_person() -> Person {
Person {
name: String::from("Unknown"),
age: 0,
}
}
}
fn main() {
let p4 = Person::default_person();
}
Java (Static Factory Method)
Person p4 = Person.defaultPerson();
✅ Way 5: Using Default Trait
#[derive(Default)]
struct Person {
name: String,
age: u32,
}
fn main() {
let p5 = Person::default();
}
5️⃣
class Person {
String name;
int age;
// Default constructor
Person() {
this.name = "";
this.age = 0;
}
}
public class Main {
public static void main(String[] args) {
Person p5 = new Person();
}
}
Function That Modifies Object (&mut self)
impl Person {
fn birthday(&mut self) {
self.age += 1;
}
}
fn main() {
let mut p = Person {
name: String::from("Rahul"),
age: 29,
};
p.birthday();
println!("Age after birthday: {}", p.age);
}
java Equivalent: Method That Modifies Object
class Person {
String name;
int age;
void birthday() {
this.age += 1; // modifies object state
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.name = "Rahul";
p.age = 29;
p.birthday(); // modifies object
System.out.println("Age after birthday: " + p.age);
}
}
Calling Function Without Object (Normal Function)
fn greet() {
println!("Hello from Rust!");
}
fn main() {
greet();
}
7️⃣
Function Types Summary Table
Different ways to create objects and different ways to call functions
Calling functions: Rust vs Java
1) Normal function (no object)
Java
static int add(int a, int b) { return a + b; }
System.out.println(add(10, 20));
Rust
fn add(a: i32, b: i32) -> i32 { a + b }
println!("{}", add(10, 20));
2) Call function using object (method call)
Java
Person p = new Person("Ashwani");
p.greet();
Rust
let p = Person::new("Ashwani");
p.greet();
Different ways to create object: examples (Java vs Rust)
A) Direct initialization
Java (constructor)
Person p = new Person("Amit", 25);
Rust (struct literal)
let p = Person { name: "Amit".to_string(), age: 25 };
Constructor / new()
Java
Person p = new Person("Ravi", 28);
Rust
let p = Person::new("Ravi", 28);
Static factory / Associated function
Java
Person p = Person.guest();
Rust
let p = Person::guest();
Default object
Java
Person p = new Person(); // if you created a no-arg constructor
Rust
let p = Person::default(); // if Person implements/derives Default
Java Full Code (One File) for object creation and function calling
File: Main.java
// Main.java
public class Main {
// 1) Normal function (no object) - static method
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("=== Java: Normal function call ===");
System.out.println("add(10, 20) = " + add(10, 20));
System.out.println("\n=== Java: Object creation ways ===");
// A) Constructor (parameterized)
Person p1 = new Person("Ashwani", 30);
p1.greet();
System.out.println("p1 nextAge = " + p1.nextAge());
// B) No-arg constructor (default object)
Person p2 = new Person();
p2.greet();
// C) Static factory method (named constructor style)
Person p3 = Person.guest();
p3.greet();
// D) Builder pattern
Person p4 = new Person.Builder()
.name("Ravi")
.age(25)
.build();
p4.greet();
System.out.println("\n=== Java: Mutating object ===");
p1.setAge(31); // mutating via setter
System.out.println("p1 age after setAge = " + p1.getAge());
System.out.println("\n=== Java: Reuse another class function by object ===");
TaxCalculator tax = new TaxCalculator();
double total = tax.totalWithTax(1000.0);
System.out.println("Total with tax on 1000 = " + total);
}
}
// "Class" in Java
class Person {
private String name;
private int age;
// B) No-arg constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// A) Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// C) Static factory method
public static Person guest() {
return new Person("Guest", 0);
}
// Instance method (object function)
public void greet() {
System.out.println("Hello, my name is " + name + ", age=" + age);
}
// Method returning value
public int nextAge() {
return age + 1;
}
// Mutators (Java allows mutation through methods)
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
// D) Builder (common real-world style)
public static class Builder {
private String name = "Unknown";
private int age = 0;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Person build() {
return new Person(name, age);
}
}
}
// Another class whose function we reuse by creating its object
class TaxCalculator {
public double totalWithTax(double amount) {
double tax = amount * 0.18; // 18%
return amount + tax;
}
}
Java Output (example)
=== Java: Normal function call ===
add(10, 20) = 30
=== Java: Object creation ways ===
Hello, my name is Ashwani, age=30
p1 nextAge = 31
Hello, my name is Unknown, age=0
Hello, my name is Guest, age=0
Hello, my name is Ravi, age=25
=== Java: Mutating object ===
p1 age after setAge = 31
=== Java: Reuse another class function by object ===
Total with tax on 1000 = 1180.0
Rust Full Code (One File) for object creation and function calling
// main.rs
// 1) Normal function (no object)
fn add(a: i32, b: i32) -> i32 {
a + b
}
// "Struct" in Rust (like class fields)
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
// Default object creation (like Java no-arg constructor)
impl Default for Person {
fn default() -> Self {
Self {
name: "Unknown".to_string(),
age: 0,
}
}
}
// "impl" in Rust (like class behavior)
impl Person {
// B) Constructor style (associated function)
fn new(name: &str, age: u32) -> Self {
Self {
name: name.to_string(),
age,
}
}
// C) Static factory style (associated function)
fn guest() -> Self {
Self {
name: "Guest".to_string(),
age: 0,
}
}
// Instance method (object function)
fn greet(&self) {
println!("Hello, my name is {}, age={}", self.name, self.age);
}
// Method returning value
fn next_age(&self) -> u32 {
self.age + 1
}
// Mutating method (requires &mut self)
fn set_age(&mut self, age: u32) {
self.age = age;
}
}
// D) Builder-style in Rust (common pattern)
struct PersonBuilder {
name: String,
age: u32,
}
impl PersonBuilder {
fn new() -> Self {
Self {
name: "Unknown".to_string(),
age: 0,
}
}
fn name(mut self, name: &str) -> Self {
self.name = name.to_string();
self
}
fn age(mut self, age: u32) -> Self {
self.age = age;
self
}
fn build(self) -> Person {
Person {
name: self.name,
age: self.age,
}
}
}
// Another struct whose function we reuse by creating its object
struct TaxCalculator;
impl TaxCalculator {
fn total_with_tax(&self, amount: f64) -> f64 {
let tax = amount * 0.18;
amount + tax
}
}
fn main() {
println!("=== Rust: Normal function call ===");
println!("add(10, 20) = {}", add(10, 20));
println!("\n=== Rust: Object creation ways ===");
// A) Direct struct initialization (struct literal)
let p1 = Person {
name: "Ashwani".to_string(),
age: 30,
};
p1.greet();
println!("p1 next_age = {}", p1.next_age());
// B) Constructor style (associated function)
let p2 = Person::new("Ravi", 25);
p2.greet();
// C) Static factory style
let p3 = Person::guest();
p3.greet();
// Default object
let p4 = Person::default();
p4.greet();
// D) Builder pattern
let p5 = PersonBuilder::new().name("Neha").age(22).build();
p5.greet();
println!("\n=== Rust: Mutating object ===");
let mut p6 = Person::new("Amit", 28);
p6.set_age(29); // needs mut + &mut self method
println!("p6 after set_age: {:?}", p6);
println!("\n=== Rust: Reuse another struct function by object ===");
let tax = TaxCalculator;
let total = tax.total_with_tax(1000.0);
println!("Total with tax on 1000 = {}", total);
}
Rust Output (example)
=== Rust: Normal function call ===
add(10, 20) = 30
=== Rust: Object creation ways ===
Hello, my name is Ashwani, age=30
p1 next_age = 31
Hello, my name is Ravi, age=25
Hello, my name is Guest, age=0
Hello, my name is Unknown, age=0
Hello, my name is Neha, age=22
=== Rust: Mutating object ===
p6 after set_age: Person { name: "Amit", age: 29 }
=== Rust: Reuse another struct function by object ===
Total with tax on 1000 = 1180
rust-interview-questions-on-functions-objects-class-concept
how-rust-replaces-classes-with-struct-impl-and-trait
Top comments (0)