Call member function of a struct in new

Say I have a struct

struct S {
    field1: String,
    field2: String,
    field3: SomeType,
}

and an impl block

impl S {
    fn new(field1: String, field2: String) -> S {
        S {
            field1,
            field2,
            field3: &self.construct_field3,
        }
    }

    fn construct_field3() -> SomeType {
        ...
    }
}

I need to know that is there a way to call construct_field3 inside the new method? Or is it done differently in rust?

Yes, associated functions can be called inside of other associated functions, either via the type name S::construct_field3 or via Self::construct_field3 (Self being a special keyword inside of impl blocks referring to the implementing type):

struct SomeType;

struct S {
    field1: String,
    field2: String,
    field3: SomeType,
}

impl S {
    fn new(field1: String, field2: String) -> S {
        S {
            field1,
            field2,
            field3: Self::construct_field3(),
        }
    }

    fn construct_field3() -> SomeType {
        todo!()
    }
}

Playground.

For more information see i.e.:

2 Likes

One follow up question on it, if the signature of construct_field3 is like fn construct_field3(&self) -> SomeType then calling construct_field3 results in the error expected 1 argument, found 0 what is the way around this error?

You can't call methods from associated functions, because there is no self instance of S around. What you can do is construct an instance of S in the new associated function and then call construct_field3 on that instance, i.e.:

struct SomeType;

struct S {
    field1: String,
    field2: String,
    field3: Option<SomeType>,
}

impl S {
    fn new(field1: String, field2: String) -> S {
        let mut s = S {
            field1,
            field2,
            field3: None,
        };
        
        s.field3 = Some(s.construct_field3());
        
        s
    }

    fn construct_field3(&self) -> SomeType {
        todo!()
    }
}

Playground.

You can read more about methods and associated functions in the book:

3 Likes