Rust is full of functions that behave exactly like constructors in other languages:
struct String {
vec: Vec<u8>,
}
impl String {
/// Creates a new string buffer initialized with the empty string.
pub fn new() -> String {
String {
vec: Vec::new(),
}
}
}
Would it be possible to introduce (optional) syntax that unifies the return type and the initializer? Like so:
impl String {
/// Creates a new string buffer initialized with the empty string.
pub fn new() -> String {
vec: Vec::new(),
}
}
This syntax would activate when the parser sees field initializers instead of statements inside a function block. It wouldn’t be dependent on name or context.
It reduces visual noise and makes it clear that the function is creating a new instance.
I don’t think you could have statements in the initializer, but you can always code it like a regular function. Visual noise/redundancy in this case isn’t an issue since the initializer block and the function signature aren’t on adjacent lines:
pub fn new() -> String {
let buffer: Vec<u8> = Vec::new();
String {
vec: buffer,
}
}