gpt4 book ai didi

crystal-lang - 如何在 "if"语句中使用 union [Crystal]

转载 作者:行者123 更新时间:2023-12-04 03:57:14 24 4
gpt4 key购买 nike

以下代码运行良好并打印“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?

I would like to stop the call of method "#+()" if $x or $y is niland print the calculated result if both are Float64.

What is the best practice for this situation?


In above code, I simplified the code for this question.In the result, the meaning of question was changed involuntarily..I wanted to ask following code actually.

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

我怎样才能避免这个错误?

最佳答案

请务必阅读有关 if 的文档,并检查是否为 nil:https://crystal-lang.org/docs/syntax_and_semantics/if_var.htmlhttps://crystal-lang.org/docs/syntax_and_semantics/if_var_nil.html

这仅适用于局部变量,因此您需要先将值分配给局部变量。

作为旁注,从 Crystal 0.19.0 开始,全局变量不再存在于语言中。

关于crystal-lang - 如何在 "if"语句中使用 union [Crystal],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39373444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com