Type Assertions
Part of the Logic & Flow section of Coddy's GO journey — lesson 17 of 68.
When working with interface variables, you often need to access the actual concrete value stored inside them. This is where type assertions come in - they allow you to safely extract and use the underlying value.
A type assertion uses this syntax: value, ok := interfaceVariable.(Type). The first return value is the extracted value of the specified type, and the second is a boolean that tells you whether the assertion was successful.
var data interface{} = 42
number, ok := data.(int)
if ok {
fmt.Println("It's an integer:", number)
} else {
fmt.Println("Not an integer")
}The ok variable is crucial for safety. If you try to assert the wrong type, ok will be false, and value will be the zero value of that type. Without checking ok, a failed type assertion would cause your program to panic.
Type assertions are essential when working with interface{} values, allowing you to convert the generic interface back to a specific type so you can use its methods and operations.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyIn this challenge, you'll practice using type assertions to safely extract and work with concrete values from interface variables. You'll create a data analyzer that processes different types of values stored in empty interfaces.
You will receive two inputs:
- A string representing the data type to check for (e.g.,
"int","string", or"bool") - A string representing the actual value (e.g.,
"42","hello", or"true")
Your task is to:
- Convert the value string to the appropriate Go type and store it in an
interface{}variable:- For
"int": convert to integer - For
"string": use as string - For
"bool": convert to boolean
- For
- Use type assertion to check if the interface variable contains the expected type specified in the first input
- If the type assertion succeeds, print:
"Success: [value] is a [type]" - If the type assertion fails, print:
"Failed: value is not a [type]"
You must use the safe type assertion syntax with the ok variable to check if the assertion was successful. The challenge tests your understanding of how to safely extract concrete values from interface variables without causing your program to panic.
For boolean conversion, "true" should convert to true and any other string should convert to false. Use the strconv package for string to integer conversion.
Cheat sheet
Type assertions allow you to extract concrete values from interface variables using the syntax value, ok := interfaceVariable.(Type):
var data interface{} = 42
number, ok := data.(int)
if ok {
fmt.Println("It's an integer:", number)
} else {
fmt.Println("Not an integer")
}The ok variable indicates whether the assertion was successful. If false, value will be the zero value of that type. Always check ok to prevent panics from failed assertions.
Try it yourself
package main
import (
"fmt"
"strconv"
)
func main() {
// Read input
var dataType string
var valueStr string
fmt.Scanln(&dataType)
fmt.Scanln(&valueStr)
// Variable to store the interface value
var interfaceValue interface{}
// TODO: Write your code below
// 1. Convert valueStr to appropriate type based on dataType and store in interfaceValue
// 2. Use type assertion to check if interfaceValue contains the expected type
// 3. Print the appropriate success or failure message
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors