Go Type Switch: Handling Diverse Data
Go's type switch is a powerful construct for elegantly handling variables that can hold values of different underlying types. This challenge will test your ability to use type switches to perform actions based on the specific type of an interface variable. This is a common pattern in Go for decoding data, processing API responses, or working with generic collections.
Problem Description
Your task is to implement a function in Go that accepts a variable of type interface{}. This variable could hold a string, an int, a float64, or a bool. Your function should perform a specific action based on the actual type of the value stored in the interface{}:
- If the value is a
string, print its length. - If the value is an
int, print its value multiplied by 2. - If the value is a
float64, print its value rounded to the nearest whole number. - If the value is a
bool, print its boolean representation (e.g., "true" or "false"). - If the value is of any other type, print an "Unknown type" message.
Examples
Example 1:
Input: "hello"
Output: 5
Explanation: The input is a string "hello". The length of the string is 5.
Example 2:
Input: 10
Output: 20
Explanation: The input is an integer 10. Multiplying it by 2 gives 20.
Example 3:
Input: 3.14159
Output: 3
Explanation: The input is a float64 3.14159. Rounded to the nearest whole number is 3.
Example 4:
Input: true
Output: true
Explanation: The input is a boolean true. Its string representation is "true".
Example 5:
Input: []int{1, 2, 3}
Output: Unknown type
Explanation: The input is a slice of integers, which is not one of the expected types.
Constraints
- The function will accept a single argument of type
interface{}. - The input will be one of the following types:
string,int,float64,bool, or any other valid Go type. - There are no specific performance constraints beyond writing clear and idiomatic Go code.
Notes
- Remember to import the necessary packages for printing output.
- For rounding the
float64, you can use themath.Roundfunction from themathpackage. - Think about how you can elegantly check for each specific type within the
interface{}variable.