- GObject, rust

Have you ever had these annoyances with GObject-style constructors?

  • From a constructor, calling a method on a partially-constructed object is dangerous.

  • A constructor needs to set up "not quite initialized" values in the instance struct until a construct-time property is set.

  • You actually need to override GObjectClass::constructed (or was it ::constructor?) to take care of construct-only properties which need to be considered together, not individually.

  • Constructors can't report an error, unless you derive from GInitable, which is not in gobject, but in gio instead. (Also, why does that force the constructor to take a GCancellable...?)

  • You need more than one constructor, but that needs to be done with helper functions.

This article, Perils of Constructors, explains all of these problems very well. It is not centered on GObject, but rather on constructors in object-oriented languages in general.

(Spoiler: Rust does not have constructors or partially-initialized structs, so these problems don't really exist there.)

(Addendum: that makes it somewhat awkward to convert GObject code in C to Rust, but librsvg was able to solve it nicely with <buzzword>the typestate pattern</buzzword>.)