【发布时间】:2020-04-14 15:08:16
【问题描述】:
我正在编写一个测试,检查一个点的坐标是否具有某个值,例如:
it "should work" do
p = do_something # returns a Point(x, y)
p.x.should eq 0 # errors (see below)
end
但是编译失败,报如下错误:
Error: undefined method 'x' for Nil (compile-time type is (Point | Nil))
我能够将问题简化为以下无法编译的最小示例:
struct Point
property x : Int32
property y : Int32
def initialize(@x, @y)
end
end
begin
p = Point.new 0, 0
ensure
p.x == 0
end
抛出同样的错误:
❯ crystal src/debug.cr
Showing last frame. Use --error-trace for full trace.
In src/debug.cr:11:7
11 | p.x == 0
^
Error: undefined method 'x' for Nil (compile-time type is (Point | Nil))
现在,我在编程语言 Github 跟踪器上遇到了类似的错误报告:Nil type check fails when using ensure,显然这是一个必须通过 Crystal 语言解决的问题。
我的问题是,如何检查p.x 的值而不在ensure 块中触发此错误?我有点不知道如何访问它。
对于上下文,我正在编写一个加密库,它对椭圆曲线上的点进行操作,所以这里就是检查坐标的一切。
【问题讨论】:
标签: unit-testing compiler-errors crystal-lang