以下代码运行良好并打印“5.0”
$x : Float64
$y : Float64
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y
现在,我更改代码以支持“nil” .
$x : Float64?
$y : Float64?
$x = 3.0_f64
$y = 2.0_f64
puts $x + $y if !$x.nil? && !$y.nil?
但是,此代码报告以下错误消息 .
no overload matches 'Float64#+' with type (Float64 | Nil)
Overloads are:
- Float64#+(other : Int8)
- Float64#+(other : Int16)
- Float64#+(other : Int32)
- Float64#+(other : Int64)
- Float64#+(other : UInt8)
- Float64#+(other : UInt16)
- Float64#+(other : UInt32)
- Float64#+(other : UInt64)
- Float64#+(other : Float32)
- Float64#+(other : Float64)
- Number#+()
Couldn't find overloads for these types:
- Float64#+(Nil)
puts $x + $y if !$x.nil? && !$y.nil?
如果$ x或$ y为nil,我想停止调用方法“#()”,如果两者都是Float64,则打印计算结果 .
这种情况的最佳做法是什么?
在上面的代码中,我简化了这个问题的代码 . 在结果中,问题的含义被不自觉地改变了......我想实际问下面的代码 .
class Xyz
property a, b
@a : Float64?
@b : Float64?
def initialize
@a = nil
@b = nil
end
def do_calc
if !@a.nil? && !@b.nil?
puts @a + @b
else
puts "We can't calculate because '@a or @b has nil."
end
end
end
x = Xyz.new
x.a = 3.0_f64
x.b = 2.0_f64
x.do_calc
此代码报告以下错误 .
instantiating 'Xyz#do_calc()'
x.do_calc
^~~~~~~
in ./a.cr:15: no overload matches 'Float64#+' with type (Float64 | Nil)
Overloads are:
- Float64#+(other : Int8)
- Float64#+(other : Int16)
- Float64#+(other : Int32)
- Float64#+(other : Int64)
- Float64#+(other : UInt8)
- Float64#+(other : UInt16)
- Float64#+(other : UInt32)
- Float64#+(other : UInt64)
- Float64#+(other : Float32)
- Float64#+(other : Float64)
- Number#+()
Couldn't find overloads for these types:
- Float64#+(Nil)
puts @a + @b
我怎样才能避免这个错误?
1 回答
请务必阅读有关if和检查nil的文档:https://crystal-lang.org/docs/syntax_and_semantics/if_var.html和https://crystal-lang.org/docs/syntax_and_semantics/if_var_nil.html
这仅适用于局部变量,因此您需要首先将值分配给局部变量 .
作为旁注,从Crystal 0.19.0开始,语言中不再存在全局变量 .