Learn how to use methods with Rust structs

Let’s look at how to use a “getter”method in Rust Programming Language. If you’ve used a getter method with object oriented languages you’ll be familiar with accessing data from an instance of a class.

The method we use will allow us to get the car name string aka “cname” from the instance of the car as defined in the struct below:

Create a struct in Rust

Create a “getter method”

If you’re used to Python classes then this should be slightly familiar, note the use of “self” inside the parentheses after the get_name fn declaration?

&self Abbreviates self: &Self
This borrows the instance immutably

You must also use the &str to specify what will be returned from the function (method).

How to use impl with a Rust struct to add a method
Watch the code to create a getter method to get a string with a struct in Rust

Full Code:

struct Car {

    cname : String,
    engine : f32,
    doors : u8,
    age : u32

impl Car {
    fn get_name(&self)->&str {

fn main(){

    let vw = Car{
        cname : String::from("Polo"),

    println!("{:?} {} {} {:?}",vw.engine, vw.doors, vw.age, vw.get_name());