Hone logo
Hone
Problems

Mastering Type Assertions in Go

Type assertions in Go are crucial for safely converting an interface{} to a specific type. This is essential when you know (or suspect) that an interface holds a value of a particular type, allowing you to access its underlying methods and fields. This challenge will test your understanding of type assertions and how to handle potential type mismatches gracefully.

Problem Description

You are given an interface interface{} named data. This interface can hold values of different types, including int, string, and float64. Your task is to write a Go function processData(data interface{}) (int, error) that attempts to convert the data to an int.

The function should:

  1. Attempt a type assertion from interface{} to int.
  2. If the assertion is successful, return the integer value and nil error.
  3. If the assertion fails (meaning data is not an int), return 0 and an error message indicating the type assertion failed. The error message should clearly state that the assertion to int failed.
  4. Handle the case where data is nil gracefully. If data is nil, return 0 and an error message indicating that a nil value cannot be asserted to an int.

Examples

Example 1:

Input: 10
Output: 10, nil
Explanation: The input is an integer, so the type assertion succeeds, and the integer value is returned along with a nil error.

Example 2:

Input: "hello"
Output: 0, "Type assertion failed: cannot convert 'string' to 'int'"
Explanation: The input is a string, so the type assertion fails, and 0 is returned along with an error message.

Example 3:

Input: 3.14
Output: 0, "Type assertion failed: cannot convert 'float64' to 'int'"
Explanation: The input is a float64, so the type assertion fails, and 0 is returned along with an error message.

Example 4:

Input: nil
Output: 0, "Cannot assert nil to int"
Explanation: The input is nil, so the type assertion fails, and 0 is returned along with an error message.

Constraints

  • The input data can be nil.
  • The input data can be of type int, string, float64, or any other type.
  • The function must return an int and an error.
  • Error messages must be descriptive and informative.

Notes

  • Use the "comma ok" idiom for type assertions to safely check if the assertion is successful.
  • Consider the possibility of nil values when performing type assertions.
  • The function should not panic under any circumstances. It should always return an int and an error.
  • Focus on clear error handling and informative error messages.
Loading editor...
go