官术网_书友最值得收藏!

Optional and keyword arguments

When defining functions, one or more arguments can be given a default value such as f(arg = val). If no parameter is supplied for arg, then val is taken as the value of arg. The position of these arguments in the function's input is important, just as it is for normal arguments; that's why they are called optional positional arguments. Here is an example of an f function with an optional argument b:

# code in arguments.jl: 
f(a, b = 5) = a + b

For example, if it's f(1), then it returns 6; f(2, 5) returns 7; and f(3) returns 8. However, calling it with f() or f(1,2,3) returns an error, because there is no matching function f with zero or three arguments. These arguments are still only defined by position: calling f(2, b = 5) raises an error as ERROR: function f does not accept keyword arguments.

Until now, arguments were only defined by position. For code clarity, it can be useful to explicitly call them by name, so they are called optional keyword arguments. Because the arguments are given explicit names, their order is irrelevant, but they must come last and be separated from the positional arguments by a semi-colon (;) in the argument list, as shown in this example:

 k(x; a1 = 1, a2 = 2) = x * (a1 + a2) 

Now, k(3, a2 = 3) returns 12, k(3, a2 = 3, a1 = 0) returns 9 (so their position doesn't matter), but k(3) returns 9 (demonstrating that the keyword arguments are optional). Normal, optional positional, and keyword arguments can be combined as follows:

function allargs(normal_arg, optional_positional_arg=2; keyword_arg="ABC") 
    print("normal arg: $normal_arg" - ) 
    print("optional arg: $optional_positional_arg" - ) 
    print("keyword arg: $keyword_arg") 
end 

If we call allargs(1, 3, keyword_arg=4), it prints normal arg: 1 - optional arg: 3 - keyword arg: 4.

A useful case is when the keyword arguments are splatted as follows:

function varargs2(;args...) 
    args 
end 

Calling this with varargs2(k1="name1", k2="name2", k3=7) returns pairs(::NamedTuple) with three entries: (:k1,"name1") (:k2,"name2") (:k3,7). Now, args is a collection of (key, value) tuples, where each key comes from the name of the keyword argument, and it is also a symbol (refer to the Strings section of Chapter 2, Variables, Types, and Operations) because of the colon (:) as prefix.

主站蜘蛛池模板: 庄浪县| 射洪县| 乌拉特后旗| 阜康市| 开封市| 柳林县| 宜宾县| 库尔勒市| 志丹县| 北票市| 长乐市| 徐闻县| 江口县| 苗栗县| 武安市| 桦南县| 玉山县| 武山县| 鲁山县| 宁乡县| 聂荣县| 曲麻莱县| 大化| 于田县| 光山县| 响水县| 嘉兴市| 洛扎县| 梅州市| 巴林左旗| 长寿区| 呼玛县| 澄迈县| 广安市| 黑水县| 昌平区| 晴隆县| 铁岭市| 涿鹿县| 桑植县| 岳普湖县|