Go (Golang) / Object-Oriented Programming in Go

Understanding Type Assertions and Type Switching

In this tutorial, we will delve into type assertions and type switching in Go. These are important concepts that allow you to work effectively with interfaces.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores how Go implements object-oriented concepts using structs and interfaces.

Understanding Type Assertions and Type Switching in Go

1. Introduction

Goal of the tutorial

This tutorial aims to provide a comprehensive understanding of type assertions and type switching in Go language.

Learning Outcomes

By the end of this tutorial, you'll be able to:
- Understand the concepts of type assertion and type switching.
- Implement type assertions and type switches in Go.
- Understand the best practices associated with these concepts.

Prerequisites

Basic understanding of Go language and its syntax.

2. Step-by-Step Guide

Type Assertions

A type assertion provides access to an interface value's underlying concrete value. It takes the form i.(T), where i is an interface value and T is the type we want to assert i is.

var i interface{} = "hello"
s := i.(string)
fmt.Println(s) //outputs: hello

In the above example, we assert the type of i to be string.

If i does not hold a T, this statement will trigger a panic. To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

s, ok := i.(string)
fmt.Println(s, ok) //outputs: hello true

Type Switches

A type switch is a construct that permits several type assertions in series. It's a way to discover the dynamic type of an interface variable.

switch v := i.(type) {
case int:
    fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
    fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
    fmt.Printf("I don't know about type %T!\n", v)
}

In the above example, the i interface variable's dynamic type is checked against the int and string types.

3. Code Examples

Here is a practical example of type assertions and type switching:

package main

import "fmt"

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("Twice %v is %v\n", v, v*2)
    case string:
        fmt.Printf("%q is %v bytes long\n", v, len(v))
    default:
        fmt.Printf("I don't know about type %T!\n", v)
    }
}

func main() {
    do(21)
    do("hello")
    do(true)
}

Output:

Twice 21 is 42
"hello" is 5 bytes long
I don't know about type bool!

This example demonstrates both type assertions and type switching. The do function takes an interface value and uses a type switch to assert its type.

4. Summary

In this tutorial, we have covered:
- The concept of type assertions and type switching in Go.
- Practical examples of type assertions and type switches.
- Best practices with these concepts.

To continue learning, consider exploring more about interfaces in Go, as they play a significant role in understanding type assertions and type switches.

5. Practice Exercises

  1. Write a function that takes an interface value and uses a type switch to assert its type to int or string. If it's neither, the function should print "unknown type".

  2. Modify the function from exercise 1 to also handle float64 type. It should print the square of the number if the type is float64.

Solutions to these exercises and more practice can be found in Go's official documentation and numerous Go programming books. Practice is key to mastering these concepts. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Name Generator

Generate realistic names with customizable options.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help