2016-09-07 4 views
3

次のコードはうまく「5.0」とプリントの作品「場合」で労働組合を使用する方法は文[クリスタル]

$x : Float64 
$y : Float64 
$x = 3.0_f64 
$y = 2.0_f64 
puts $x + $y 

は今、私が「ゼロ」をサポートするためにコードを変更します。

$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ある場合、算出結果を印刷する場合、私は「)(#1 +」のメソッドの呼び出しを停止したいです。

この状況のベストプラクティスは何ですか?


上記のコードでは、この質問のコードを簡略化しました。 その結果、質問の意味が無意識に変わってしまった。 実際に次のコードを尋ねたかった。

class Xyz 
    property a, b 
    @a : Float64? 
    @b : Float64? 

    def initialize 
    @a = nil 
    @b = nil 
    end 

    def do_calc 
    if [email protected]? && [email protected]? 
     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 

このエラーを回避するにはどうすればよいですか?

答えて

4

は、ifに関するドキュメントを必ずお読みください、そしてゼロのチェック: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以降の言語ではもう存在しません。

+0

ご質問ありがとうございます。私はこの質問のコードを簡略化しました。 その結果、質問の意味が無意識のうちに変更されました。 私は実際に質問したい質問を追加しました。 – elgoog

+0

あなたが指定したリンクの回答が見つかりました。重複した質問を申し訳ありません。 – elgoog

関連する問題