Rust support overloading constructor?


#1

when i use overloading constructor, it error. So, rust lang support overloading constructor?. This is code:

use std::result;
 use std::fmt;
 pub struct SomeObj{
    someobj1: String,
    someobj2: i32,
    someobj3: i32,
}

    /* FIXME: constructor and get set*/
    /* FIXME: constructor*/
impl SomeObj{
    
    pub fn newtest(someobj1: &str, someobj2: i32, someobj3: i32)->SomeObj{    
        SomeObj{someobj1:someobj1.to_string(),
               someobj2:someobj2,
               someobj3:someobj3,    
            }
        }
}
    pub fn newtest(someobj1: &str, someobj2: i32)->SomeObj{    
        SomeObj{someobj1:someobj1.to_string(),
               someobj2:someobj2,    
            }
        }

impl Clone for SomeObj{
        fn clone (&self)-> SomeObj{
        SomeObj{
            someobj1:self.someobj1.clone(),
            someobj2:self.someobj2.clone(),
            someobj3:self.someobj3.clone()
        }
    }
}

/* FIXME: set and get*/
 impl SomeObj{
    pub fn setsomeobj1 (&mut self, someobj1_c: &str){
        self.someobj1 = someobj1_c.to_string(); 
    }
    pub fn getsomeobj1 (&self)-> String{
        self.someobj1.to_string()
    }
    
    pub fn setsomeobj2 (&mut self, someobj2_c: i32){
        self.someobj2 = someobj2_c;
    }
    pub fn getsomeobj2 (&self)->i32{
         self.someobj2
    }
    
    pub fn setsomeobj3 (&mut self, someobj3_c: i32){
        self.someobj3 = someobj3_c;
    }
    pub fn getsomeobj3 (&self)->i32{
        self.someobj3
    } 
}

/* Error:
pub fn newtest(someobj1: &str, someobj2: i32)->SomeObj{
SomeObj{someobj1:someobj1.to_string(),
someobj2:someobj2,
}
}
missing field: someobj3 [E0063]
src/libtest/api.rs:22 SomeObj{someobj1:someobj1.to_string(),
src/libtest/api.rs:23 someobj2:someobj2,
src/libtest/api.rs:24 }
src/libtest/api.rs:22:3: 24:5 help: run rustc --explain E0063 to see a detailed
*/


#2

What is SomeObj?


#3

this is struct SomeObj.
pub struct SomeObj{
someobj1: String,
someobj2: i32,
someobj3: i32,
}


#4

Attach error log.


#5

You cannot have two methods with the same name. The common pattern is to have multiple methods (e.g. new, with_x, from_y), or use the Builder pattern if the number of combinations gets out of hand.


#6

Could you please reformat your code. Include all your code inside of
```
your code
```


#7

Rust does not support functions with same name.


#8

Please see preview before submit. It looks ugly and chance to confuse is big.


#9

can I how to solve problem?


#10

You should use different function names.
Choose main constructor and name it new.
Name another constructor somehow else.


#11

Thanks you.


#12

You can implement From (or a trait similar to From) with all types you want to construct with. These can be a tuple.


#13

I think this is smelling hack. Don’t you think so?


#14

No. The most general use case for overloaded constructors is precisely constructing a type B From type A.