How would I assign values using the impl and structs?

fn main()
{
    let color = Color::initialize()
}
struct Color
{
    blue: u32,
    green: u32,
    yellow: u32,
    red: u32,
}

impl Color
{
    fn initialize(&mut self)
    {
        self.blue   =   0x3b47f7;
        self.green  =   0x14a03e;
        self.yellow =   0xc6e035;
        self.red    =   0xdd382c;
    }
}

I want to create a method inside impl that will initialize the variables by assigning its values. But this doesn't seem to work. I tried passing in &self but I can't edit the values. Does anyone know what I need to do to fix this?

Since initialize takes a &mut self, you need an existing Color to pass in, but you don't have one in main. It looks like you want the function to return a new Color; this would look like

impl Color {
    fn new() -> Self {
        Self {
            blue: 0x3b47f7,
            green: 0x14a03e,
            yellow: 0xc6e035,
            red: 0xdd382c,
        }
    }
}

fn main() {
    let color = Color::new();
}
1 Like

I see, thanks.

But what is the difference between the lowercase self and Self? How come you are not using a reference?

Self (in an impl block) is a the type you're implementing for. For example, if we're in a impl Color block, Self is just shorthand for Color. self is an argument of type Self, passed as the first parameter to a method (you can read self in an argument as self: Self, &self as self: &Self, and &mut self as self: &mut Self.) If you have a function like fn foo(self, ...), it can be called like self.foo(...).

new doesn't take a reference because there's nothing that it needs to take a reference to; it doesn't return a reference because we're creating a new Color and returning it, transferring ownership.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.