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.
Loading...
Related Quiz
- In Go, a _______ is a function that runs concurrently with other functions.
- In a transaction, what does the "rollback" operation signify?
- When accessing a map value in Go, a second optional _____ value can be used to check if the key exists.
- Describe the concept of struct embedding in Go.
- What are the potential downsides of over-mocking in tests?