我无法访问 defrecord 对象的内部字段。所有标准方法都返回 nil

I cannot access the inner field of a defrecord object. All standard approaches keep returning nil

提问人:Braden Christopher 提问时间:10/18/2023 最后编辑:Alan ThompsonBraden Christopher 更新时间:10/18/2023 访问量:97

问:

本质上,我有一个名为“Cell”的对象,在输出时看起来像这样。我只是试图访问其中的字段。不过,每当我尝试时,我都会得到.sample-cell[#grid_generator.core.Cell{:coordinates [1.0 1.0], :value 3.0}]:coordinates(:coordinates sample-cell)nil

我一辈子都无法弄清楚为什么我的代码不起作用。我也尝试过相同的结果(以防万一出现嵌套问题),但我仍然遇到同样的问题。这是我的第一个项目,所以我预计会有一些挂断。任何帮助都是值得赞赏的!谢谢!get-in

函数式编程 Clojure Lisp

评论

1赞 Harold 10/18/2023
欢迎进来 - 分享您的代码的最小示例,我相信这里的众多专家中的一位会立即发现这个问题。从您分享的内容来看,也许您需要,但没有足够的上下文可以肯定地说。(::coordinates sample-cell)

答:

3赞 Rulle 10/18/2023 #1

从打印输出来看,您似乎已将单元格放入一个向量中,该单元格是单个元素:

(defrecord Cell [coordinates value])

(def sample-cell [(Cell. [1.0 1.0] 3)])

sample-cell
;; => [#grid_generator.core.Cell{:coordinates [1.0 1.0], :value 3}]

仅仅要求在该向量中查找密钥是行不通的::coordinates

(:coordinates sample-cell)
;; => nil

然而,有效的方法是首先请求该向量中的元素,然后得到:first:coordinates

(:coordinates (first sample-cell))
;; => [1.0 1.0]

...或者,您可以简单地解决假定的根本问题,并确保它恰好是:sample-cellCell

(def sample-cell (Cell. [1.0 1.0] 3))

(instance? Cell sample-cell)
;; => true