this post was submitted on 27 Dec 2024
10 points (64.7% liked)

Rust

6141 readers
40 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 2 years ago
MODERATORS
 

Hello,

I learned about struct in Rust, so I just wanted to share what I have learned.

what is struct in Rust? It's the same as what's in C language. eg,

struct Point {
    x: i32,
    y: i32,
}

that's it this is how we define a struct. we can create all sort of struct with different data types. ( here I have used only i32 but you can use any data type you want)

now Rust also have which we find in OOPs languages like Java. it's called method. here is how we can define methods for a specific struct in Rust.

impl Point {
    fn print_point(&self) {
        println!("x: {} y: {}", self.x, self.y);
    }
}

see it's that easy. tell me if I forgot about something I should include about struct in Rust.

you are viewing a single comment's thread
view the rest of the comments
[–] TehPers@beehaw.org 1 points 1 day ago

In other languages, these are usually called static methods. Rust just uses these instead of constructor methods. That way you never have to work with a partially initialized value - you just create the value in your new function once you've initialized all its fields.