關鍵字參數
關鍵字參數是另一種可以傳入函式的參數型式。它的概念和前一章看到的 NamedTuple 類似——為數值指定一個名稱,讓我們更清楚該數值代表什麼。
若要宣告關鍵字參數,在函式宣告中使用分號 ; 來標示關鍵字參數。
function my_func(; my_arg)
return my_arg
end
實際呼叫函式時,分號不是必要的。
my_func(; my_arg=1)
請記住,你可以在同一個函式裡同時使用位置參數與關鍵字參數,不過在函式宣告中,關鍵字參數必須一律放在位置參數之後。
本練習屬於課程
Julia 中級
練習說明
- 將
my_profit函式改寫為使用關鍵字參數。 - 呼叫
my_profit,並對調參數順序,先傳入current_price=100.0,再傳入previous_price=105.0。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define my_profit with keyword arguments and a default argument
function my_profit(____previous_price::Float64, current_price::Float64, fees::Int64=2)
return current_price - previous_price - fees
end
# Call my_profit
my_profit(____, ____)