I sometimes find it useful to be able to take a struct object and see its slots and values. But if I evaluate a struct object I only see its values, not the names of the slots. E.g. if I have a struct like:
(cl-defstruct apple type color price)
(setq my-apple (make-apple :type "granny smith" :color "green" :price 2))
and I evaluate my-apple
, I get the printed representation of the record: #s(apple "granny smith" "green" 2)
.
I've written a function that takes any struct-object and outputs a list of the slots and values:
(defun my/print-struct (struct)
(let* ((struct-type (aref struct 0))
(slots (cdr (mapcar 'car (cl-struct-slot-info struct-type)))))
(cl-loop for slot in slots
collect (let* ((struct-type-name (symbol-name struct-type))
(slot-name (symbol-name slot))
(slot-getter (intern (format "%s-%s"
struct-type-name
slot-name))))
`(,slot ,(funcall slot-getter struct))))))
(my/print-struct my-apple)
returns ((type "granny smith") (color "green") (price 2))
.
All this is fine for my purposes, but it seems very hacky. How can I improve it?