Bắt đầu ngayBắt đầu miễn phí

Keyword arguments

Keyword arguments are another type of argument that can be passed to a function. A keyword argument is similar in concept to the NamedTuple that we saw in the previous chapter - it gives us a name to assign to a value, which gives us a good understanding of what that value actually represents.

To declare a keyword argument, we use a semicolon ; in the function declaration to denote a keyword argument.

function my_func(; my_arg)
    return my_arg
end

When actually calling the function, the semicolon is not required.

my_func(; my_arg=1)

Keep in mind that while you can mix both positional and keyword arguments in the same function, keyword arguments must always come after positional arguments in a function declaration.

Bài tập này là một phần của khóa học

Intermediate Julia

Xem khóa học

Hướng dẫn bài tập

  • Re-write the my_profit function to use keyword arguments.
  • Call my_profit but flip the order of the arguments, passing current_price=100.0 first, followed by previous_price=105.0.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# 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(____, ____)
Chỉnh sửa và Chạy Mã