Library contents

Go Comma-ok type assertion

A two-result type assertion checks the dynamic type of an imported value.

A simple example

Comma-ok type assertion

  1. Start with Text "2" where an integer is required
  2. Do this Check or cast the type
  3. Result Type mismatch
A string containing a digit is still a string. Parsing would be a separate operation.

Syntax

Go syntax
fare, ok := value.(int)
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Check the type of an imported fare

A transit app imports fares from two ticket machines. One machine sends the word “free” in a field normally filled with a whole number, so the importer needs to flag the record for review.

From the programvar imported any = "free"
ResultReview fare type
main.go
package main

import (
    "fmt"
)

func main() {
    var imported any = "free"
    if fare, ok := imported.(int); ok {
        fmt.Println(fare)
    } else {
        fmt.Println("Review fare type")
    }
}
Output
Review fare type

The imported value holds text. The desk flags the fare before treating it as a number.

Advertisements

Import a museum headcount

The counter sends the number 36 as an integer object. The import expects an integer value. Flag a text field for review before calculating a total.

GivenInteger 36
Worked resultNumber accepted

Review a quoted fare

A new terminal sends its fare as text in a field that previously carried an integer. The import expects an integer value. Flag a text field for review before calculating a total.

GivenText “36”
Worked resultReview field type

What to watch for

A failed assertion sets ok to false. The numeric zero result alone cannot tell a free fare from a wrong type.

Documentation for Comma-ok type assertion