Array of different types

This page was created on Thu Sep 08 2016 and last changed on Sat Oct 05 2024.

This is an example Go program which demonstrates building an array consisting of different types of data using interface and a type switch:

package main

import "fmt"

func main() {
        array := []interface{}{1, 2, "apple", true}
        for _, element := range array {
                switch v := element.(type) {
                case int:
                        fmt.Printf("It's a number, %d.\n", v)
                case string:
                        fmt.Printf("It's a string, '%s'.\n", v)
                case bool:
                        fmt.Printf("It's a boolean, %t.\n", v)
                default:
                        fmt.Printf("I can't handle %q.\n", v)
                }
        }
}

(download)

The output of the example looks like this:

It's a number, 1.
It's a number, 2.
It's a string, 'apple'.
It's a boolean, true.

Web links


Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer