My understanding of a struct is that it has slots to store data in, has a type, has make-X
and slot-accessor functions, and can be specialized on by a method (since it has a type).
My understanding of a class is that it has all of the same and multiple inheritance. The top answer to this question states that structs can have single inheritance, and that initial implementations of CLOS were "much slower" than structs.
Based on how people talk about CLOS and structs, I assume there must be some other differences, but my trivial google searches have been fruitless. So I ask: what are the practical differences between CLOS and structs?
Structures
Structures are more primitive. They provide what often is called a record in programming languages. They were invented before classes. CLtL1 (the first book describing Common Lisp) in 1984 already had structures and later a standard object system called CLOS was added. Structures provide
DEFSTRUCT
useful additions:
Limitations:
Extensions
CLOS classes
CLOS was invented in the mid/late 80s based on two earlier object systems (Flavors and LOOPS). It provides:
DEFCLASS
limitations:
DEFCLASS
definitions are not very conciseextensions
Common Lisp
In some cases the Common Lisp standard does not say how a functionality should be implemented: structures, classes, or maybe even something else. Examples are streams and conditions. It's usually a good sign (for added flexibility) if a Common Lisp implementation uses CLOS for those.
defstruct
does more work for you behind the scenes, e.g.:
print-object
methodAlso, structure slot access is faster (although the difference is probably inconsequential).
The bottom line is that, unless you need MOPish features, you can get away with defsrtuct
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With