Monday, May 17, 2021

Defining and Creating a New Instance in Rust

Let say we want to allow the user to create a new draft of post with Post::new , then we want to allow the user to add some text into content by using method set_content and get the text from the get method by using get_content

We need a public Post struct that holds some content of string, so let's start with the definition of the struct and associated public new method to create an instance of Post.

In the Post::new method, we set the content field to a new using String::new. We will define a public method named set_content and pass it a &str that's then added to the text content and we will implement a public method named get_content and will return &str so that the user will able to get the content.



pub struct Post {
    content: String,
}

impl Post {
    pub fn new() -> Post {
        Post {
            content: String::new(),
        }
    }

    pub fn get_content(&self) -> &str {
        &self.content
    }

    pub fn set_content(&mut self, text: &str) {
        self.content.push_str(text);
    }
}

fn main() {
    let mut post = Post::new();

    post.set_content("Implementing an Object-Oriented Design Pattern");
    println!("{}", post.get_content());
}


From terminal run  cargo build  to compile and cargo run to see the result. Finally, you will see text content Implementing an Object-Oriented Design Pattern.



Thank you







No comments:

Post a Comment