I have structure A which have embedded structure B. Sometimes struct B must get field of A.
For example struct Widget has field Font. Implementation method of Font calls CreateFontIndirectW and next SendMessageW with owner's field hwnd. I can't "font : Font::new(&self)" in constructor because constructor has not field self;
Similar problem of lack self in constructor is settings c-arrays: I have lfFaceName: unsafe { mem::zeroed() }, whereas better would be:
let face_name_ptr = (&mut font_struct.lfFaceName).as_mut_ptr();
to_array(face_name_ptr, winapi::LF_FACESIZE, "Arial");
but how to make in constructor?
There are no constructors in Rust. new()
is just a convention for a regular function, so if you have struct Font
, then Font {}
is the instance of it.
impl Widget {
fn new() -> Widget {
let widget = Widget {font: None}; // or use a default font if you don't want Option<Font>
let font = Font::new(&widget);
widget.font = Some(font);
widget
}
Please keep in mind that in Rust a struct is not allowed to hold a reference to itself (nor reference to anything in itself), so if Widget
contains a Font
, then Font
is not allowed to keep a reference to the Widget
. When you compose structs use only owned values, or Rc
if you can't avoid parent references.
1 Like