๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Go Type Assertions in Depth

A type assertion pulls the concrete value out of an interface value. The comma-ok form also reports whether the pull worked.

Comma-ok success and failure

The stored value is a string. The first assertion asks for a string, and the second asks for an int.

package main

import "fmt"

func main() {
	var value any = "hello"
	text, ok := value.(string)
	fmt.Println(text, ok)
	number, ok := value.(int)
	fmt.Println(number, ok)
}

One line for each type

A type switch tests a value against several types. Each case names one type and runs only for that type.

package main

import "fmt"

func main() {
	values := []any{42, "Go", true}
	for _, value := range values {
		switch v := value.(type) {
		case int:
			fmt.Println("int", v)
		case string:
			fmt.Println("string", v)
		case bool:
			fmt.Println("bool", v)
		}
	}
}

Fields after an assertion

The stored value is a Book. The assertion pulls the Book out, and the code reads its two fields.

package main

import "fmt"

type Book struct {
	Title string
	Pages int
}

func main() {
	var value any = Book{Title: "Go Basics", Pages: 120}
	book, ok := value.(Book)
	if ok {
		fmt.Println(book.Title)
		fmt.Println(book.Pages)
	}
}

Example

package main

import "fmt"

func main() {
	values := []any{10, "pen", 20, "book", true, 30}
	intCount, stringCount, boolCount := 0, 0, 0
	for _, value := range values {
		switch value.(type) {
		case int:
			intCount++
		case string:
			stringCount++
		case bool:
			boolCount++
		}
	}
	fmt.Println("Ints:", intCount)
	fmt.Println("Strings:", stringCount)
	fmt.Println("Bools:", boolCount)
}

Key points

  • The comma-ok form returns the concrete value and a bool.
  • A true bool means the stored value has the asked type.
  • A failed assertion gives the zero value of the asked type and a false bool.
  • A type switch tests one value against several types in a single statement.
  • Each case of a type switch names one type.
  • A count kept in a switch case can total how many values have each type.

In this example, the list holds six values of three types. The loop visits each value in list order. The type switch adds one to the count for the type of each value. Three values are ints, two are strings, and one is a bool. The three print lines show the final counts.

Note

An assertion without the comma-ok form stops the program when the type is wrong.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

A comma-ok assertion asks for an int, but the stored value is a string. What does the bool hold?