bhylu.com

Advertisements

Go Type Assertions

Check the concrete value stored inside an interface.

How it works

any is an alias for the empty interface. It can contain a value of any type, but that flexibility removes compile-time knowledge of the stored operations. A comma-ok assertion checks a candidate type without panicking; a type switch handles several possible types.

Run this Go example

Install Go separately from the official Go downloads and check go version in a new terminal. The reviewed baseline is Go 1.27.3 on Windows amd64; the authored syntax and standard-library APIs require Go 1.22 or newer. Save the complete source below as type-assertions.go in a learning folder, then run go run type-assertions.go from that folder. These examples use only the standard library.

Bhylu has no Go browser runner. Apache, MySQL, PHP and the JavaScript or Python playground are not required to run these files. File examples own a temporary directory; HTTP client examples create an ephemeral loopback server and close it. They do not contact an external API.

Download the complete type-assertions.go · Download all source files with hash checks

For the optional collection download, save download-examples.mjs in a new learning folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/go/. The downloader refuses an existing bhylu-go-examples folder and installs or executes no Go code.

Example

type-assertions.go

package main

import (
	"fmt"
)

func main() {
	var value any = "P-17"
	text, ok := value.(string)
	_, integer := value.(int)
	fmt.Println(text, ok, integer)
	switch v := value.(type) {
	case string:
		fmt.Println(len(v))
	default:
		fmt.Println("unsupported")
	}
}

Expected result

P-17 true false
4

The successful assertion returns the string. The failed int assertion returns its zero value and false. The switch variable has the case-specific type inside that branch.

For language rules and APIs, use the Go language specification and standard-library documentation. The fictional examples are learning fixtures, not a deployed parcel service.