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

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.

主站蜘蛛池模板: 河间市| 从化市| 久治县| 濮阳市| 柳州市| 兴山县| 云霄县| 九江县| 广丰县| 灌南县| 哈密市| 华宁县| 阜南县| 永清县| 松潘县| 闽侯县| 筠连县| 庐江县| 浦东新区| 怀远县| 托里县| 渝中区| 沙坪坝区| 孙吴县| 雷波县| 滦平县| 榆树市| 南岸区| 当阳市| 茂名市| 信宜市| 古丈县| 苍梧县| 江都市| 怀柔区| 扎赉特旗| 七台河市| 敖汉旗| 安平县| 手游| 西宁市|