Array of different types

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)
                        fmt.Printf("I can't handle %q.\n", v)


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 ( or use the discussion group at Google Groups. / Privacy / Disclaimer