型別宣告
我們可以對函式參數施加的另一種控制,就是指定參數的型別。你可以為每個變數指定資料型別,就像上一章在 tuple 中做的一樣。如果傳入函式的引數型別與定義函式時宣告的型別不相符,就會拋出錯誤。
這是另一種控制函式並避免不必要例外的方法。在目前版本的 my_profit 函式中,你其實可以把字串傳給每個引數,但當回傳敘述嘗試以字串相減時就會出錯。我們可以透過為每個參數定義資料型別來防範這種情況。
在下面的例子中,請為函式中的每個參數設定資料型別。
注意:如果嘗試傳入與我們定義不相符的型別,會出現以下錯誤:
MethodError: no method matching my_profit(::Int64, ::Int64)
本練習屬於課程
Julia 中級
練習說明
- 為每個參數設定資料型別,其中
current_price和previous_price應為Float64,而fees應為Int64。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define my_profit with three type-restricted arguments
function my_profit(previous_price____, current_price____, fees____=2)
return current_price - previous_price - fees
end
# Call my_profit, passing in values of the correct data type
my_profit(100.00, 105.00)