Types, Type Assertions, and Type Switches Flashcards
(6 cards)
1
Q
Type Assertions
A
Check/Extract Underlying Type (Interfaces):
var val interface{} = "hello" str := val.(string) // Basic assertion fmt.Println(str) // "hello" num, ok := val.(int) // Safe assertion if !ok { fmt.Println("Not an int!") }
Panics if wrong type:n := val.(int) // PANIC if val isn't int
2
Q
Type Switches
A
Check Multiple Types:
func printType(x interface{}) { switch v := x.(type) { case int: fmt.Printf("int: %d\n", v) case string: fmt.Printf("string: %s\n", v) default: fmt.Printf("unexpected type %T\n", v) } }
Key Points:
* v is automatically the correct type in each case
* default handles non-matched types
3
Q
Custom Types
A
Type Declarations:
type Celsius float64 // New type (not alias) type ID string
Methods:
func (c Celsius) ToF() Fahrenheit { return Fahrenheit(c*9/5 + 32) }
4
Q
Empty Interface (interface{})
A
Accepts Any Type:
var anything interface{} anything = 42 // int anything = "hello" // string anything = struct{}{} // struct
Use Cases:
* Generic functions (before generics existed)
* JSON unmarshaling
5
Q
Type Assertions vs. Conversions
A
Feature Type Assertion Type Conversion
Target Interfaces Concrete types
Syntax x.(T) T(x)
Panics If type mismatch If impossible
Safe Form val, ok := x.(T) N/A
6
Q
Practical Examples
A
JSON Handling:
var data interface{} json.Unmarshal([]byte(`{"key":42}`), &data) // Type assertion for nested access m := data.(map[string]interface{}) fmt.Println(m["key"].(float64)) // JSON numbers → float64
Error Handling:
if err != nil { if se, ok := err.(*os.SyscallError); ok { fmt.Println("Syscall error:", se.Err) } }