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

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.

主站蜘蛛池模板: 云安县| 安乡县| 璧山县| 区。| 尼木县| 顺昌县| 怀集县| 华亭县| 洛川县| 吉木萨尔县| 乐山市| 白河县| 司法| 云安县| 开远市| 海林市| 额尔古纳市| 桑植县| 阳山县| 武宣县| 全南县| 柏乡县| 大悟县| 沁阳市| 宿迁市| 白沙| 绵阳市| 白银市| 溆浦县| 武强县| 盐边县| 丰城市| 宝鸡市| 林州市| 皮山县| 莲花县| 康马县| 湄潭县| 濉溪县| 勐海县| 保亭|