In a large Go codebase, you encounter a function that accepts an empty interface (interface{}). How would you determine the underlying type of the interface safely within the function?

  • Reflection
  • Type Assertion
  • Type Assertion with Comma-ok
  • Type Switch
When encountering a function that accepts an empty interface (interface{}), one way to safely determine the underlying type within the function is to use type assertion with comma-ok idiom. This idiom allows you to safely test if the underlying type matches the expected type by providing both the type assertion and a boolean value indicating whether the assertion succeeded or not. Type switch is another way to determine the underlying type but it's more suitable when dealing with multiple types. Reflection provides a way to inspect types at runtime but it's generally not recommended due to its complexity and performance overhead. Direct type assertion without comma-ok can lead to runtime panics if the underlying type doesn't match the expected type.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *