Type Switch
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 30 of 107.
When you need to check an interface value against multiple possible types, writing separate type assertions becomes tedious. A type switch provides a cleaner way to handle this by combining a switch statement with type checking.
The syntax looks like a regular switch, but uses the special .(type) syntax:
func describe(value any) {
switch v := value.(type) {
case int:
fmt.Println("Integer:", v*2)
case string:
fmt.Println("String of length:", len(v))
case bool:
fmt.Println("Boolean:", v)
default:
fmt.Println("Unknown type")
}
}The variable v takes on the concrete type within each case block. In the int case, v is an int, so you can perform arithmetic. In the string case, v is a string, so you can call len().
You can also group multiple types in a single case:
switch v := value.(type) {
case int, int64, float64:
fmt.Println("It's a number")
case string:
fmt.Println("String:", v)
}When grouping types, v remains the original interface type since the compiler can't determine which specific type matched. The default case handles any type not explicitly listed, making your code robust against unexpected inputs.
Challenge
EasyLet's build a value classifier that uses type switches to analyze different types of data and produce meaningful descriptions. You'll create a system that can handle multiple value types and provide type-specific information about each one.
You'll organize your code across two files:
classifier.go: Create a function calledClassifythat takes a value of typeanyand returns a descriptive string. Use a type switch to handle the following types:- For
int: return whether the number is positive, negative, or zero - For
string: return the string's length category (short, medium, or long) - For
bool: return a human-readable representation - For
float64: return whether it's a whole number or has decimals - For any other type: return an unknown type message
- For
main.go: Read values from input, convert them to appropriate types, store them inanyvariables, and use yourClassifyfunction to analyze each one. Print the classification result for each value.
The following inputs will be provided:
- Line 1: An integer value
- Line 2: A string value
- Line 3: A boolean value (
trueorfalse) - Line 4: A float value
Your Classify function should return strings in these formats:
- For
int:Integer: positive,Integer: negative, orInteger: zero - For
string:String: short(length 1-5),String: medium(length 6-10), orString: long(length > 10) - For
bool:Boolean: yes(if true) orBoolean: no(if false) - For
float64:Float: whole(if no decimal part) orFloat: decimal(if has decimal part) - For unknown types:
Unknown type
For example, given -5, hello, true, and 3.14, your output should be:
Integer: negative
String: short
Boolean: yes
Float: decimalThe type switch gives you access to the concrete type within each case, so you can perform type-specific operations like comparing integers to zero or checking string length directly on the switched variable.
Cheat sheet
A type switch allows you to check an interface value against multiple possible types in a clean way, combining a switch statement with type checking.
Basic type switch syntax using .(type):
func describe(value any) {
switch v := value.(type) {
case int:
fmt.Println("Integer:", v*2)
case string:
fmt.Println("String of length:", len(v))
case bool:
fmt.Println("Boolean:", v)
default:
fmt.Println("Unknown type")
}
}The variable v takes on the concrete type within each case block, allowing type-specific operations.
You can group multiple types in a single case:
switch v := value.(type) {
case int, int64, float64:
fmt.Println("It's a number")
case string:
fmt.Println("String:", v)
}When grouping types, v remains the original interface type. The default case handles any type not explicitly listed.
Try it yourself
package main
import (
"fmt"
"strconv"
)
func main() {
// Read the integer value
var intStr string
fmt.Scanln(&intStr)
intVal, _ := strconv.Atoi(intStr)
// Read the string value
var strVal string
fmt.Scanln(&strVal)
// Read the boolean value
var boolStr string
fmt.Scanln(&boolStr)
boolVal, _ := strconv.ParseBool(boolStr)
// Read the float value
var floatStr string
fmt.Scanln(&floatStr)
floatVal, _ := strconv.ParseFloat(floatStr, 64)
// TODO: Store each value in an 'any' variable
// TODO: Call Classify() for each value and print the result
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool