Go Function Creation: Basic Calculator
This challenge involves creating a simple calculator function in Go. You'll need to implement a function that takes two numbers and an operator as input and returns the result of the operation. This is a fundamental task for understanding function definition and basic arithmetic operations in Go.
Problem Description
Your task is to write a Go function named Calculate that performs basic arithmetic operations. The function should accept three arguments:
num1(float64): The first operand.num2(float64): The second operand.operator(string): The operator to perform. This can be "+", "-", "*", or "/".
The function should return two values:
result(float64): The outcome of the calculation.err(error): An error object if the operation is invalid (e.g., division by zero, unknown operator). If the operation is successful,errshould benil.
Key Requirements:
- Implement the
Calculatefunction in Go. - Handle addition, subtraction, multiplication, and division.
- Return an error for division by zero.
- Return an error for any operator other than "+", "-", "*", or "/".
Expected Behavior: The function should perform the specified operation and return the correct result. If an error occurs, it should return a meaningful error message.
Edge Cases:
- Division by zero.
- Invalid operator input.
Examples
Example 1:
Input: num1 = 10.5, num2 = 5.2, operator = "+"
Output: result = 15.7, err = nil
Explanation: The function successfully adds 10.5 and 5.2.
Example 2:
Input: num1 = 20.0, num2 = 4.0, operator = "/"
Output: result = 5.0, err = nil
Explanation: The function successfully divides 20.0 by 4.0.
Example 3:
Input: num1 = 10.0, num2 = 0.0, operator = "/"
Output: result = 0.0, err = "division by zero is not allowed"
Explanation: Division by zero is an invalid operation, so an error is returned. The result value can be anything in this case, but 0.0 is a common default.
Example 4:
Input: num1 = 7.0, num2 = 3.0, operator = "%"
Output: result = 0.0, err = "unsupported operator: %"
Explanation: The operator "%" is not supported, so an error is returned.
Constraints
num1andnum2will be floating-point numbers (float64).operatorwill be a string.- The function should return an error for invalid operations, not panic.
- The performance requirements are minimal; focus on correctness.
Notes
- You will need to import the
errorspackage for creating custom error messages. - Consider using a
switchstatement for handling different operators. - Make sure to handle the case where
num2is zero specifically for the division operation.