From the course: Rust Programming: From Fundamentals to Advanced Concepts with AI-Assisted Development

Unlock this course with a free trial

Join today to access over 24,700 courses taught by industry experts.

Demo: Associated functions and constructors

Demo: Associated functions and constructors

- [Instructor] Some structs are fine to have in a simple definition like we do here, where you have a user struct, right? So we have a username, an email, uri, and if it's active or not, so we're having a Boolean there. So that's fine, and you might start populating that, that's fine. But in some other cases, you may want to have a constructor. Now, a constructor is a powerful way of automating tedious, repetitive things. And in this case, we might want to provide an easy way to create a user. Now, how do you do that in Rust is with an associated function. An associated function is a function that doesn't require Self, but I'm getting ahead of myself. Let's start looking at how we can do this. And we're going to start by using the implementation that implements a keyword by using impl. So implement some functionality for a type. This is not only specific for structs, but it's definitely allows us to extend struct by using stuff, by adding functions and adding some code related to it…

Contents