ComeçarComece de graça

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.

Este exercício faz parte do curso

Intermediate Julia

Ver curso

Instruções do exercício

  • 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.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

# 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(____, ____)
Editar e executar o código