Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

In 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:

  1. 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
  2. Use type assertion to check if the interface variable contains the expected type specified in the first input
  3. If the type assertion succeeds, print: "Success: [value] is a [type]"
  4. 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
	
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow