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

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.

主站蜘蛛池模板: 宣恩县| 太湖县| 呈贡县| 肥乡县| 高州市| 卓资县| 炉霍县| 东至县| 扬州市| 宁南县| 阜南县| 若羌县| 渝北区| 玉环县| 旬邑县| 收藏| 铜梁县| 南投县| 云梦县| 肥城市| 元朗区| 岢岚县| 宁化县| 瑞昌市| 武宁县| 沁水县| 绥中县| 肇源县| 南和县| 静海县| 巴彦淖尔市| 保德县| 揭阳市| 建湖县| 大连市| 北京市| 武汉市| 杨浦区| 泗洪县| 衡山县| 商都县|