github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume1/section3/emptyinterfacedemo/emptyinterfacedemo.go (about)

     1  // An example of an empty interface, and some useful things we can do with it.
     2  package main
     3  
     4  import (
     5  	"fmt"
     6  	"math/rand"
     7  	"time"
     8  
     9  	"github.com/EngineerKamesh/gofullstack/volume1/section3/simpleshape"
    10  )
    11  
    12  func giveMeARandomShape() interface{} {
    13  
    14  	var shape interface{}
    15  	var randomShapesSlice []interface{} = make([]interface{}, 2)
    16  
    17  	// Seed the random generator
    18  	s := rand.NewSource(time.Now().UnixNano())
    19  	r := rand.New(s)
    20  
    21  	// Pick a random number, either 1 or 0
    22  	randomNumber := r.Intn(2)
    23  	fmt.Println("Random Number: ", randomNumber)
    24  
    25  	// Let's make a new rectangle
    26  	rectangle := simpleshape.NewRectangle(3, 6)
    27  
    28  	// Let's make a new triangle
    29  	triangle := simpleshape.NewTriangle(9, 18)
    30  
    31  	// Let's store the shapes into a slice data structure
    32  	randomShapesSlice[0] = rectangle
    33  	randomShapesSlice[1] = triangle
    34  	shape = randomShapesSlice[randomNumber]
    35  
    36  	return shape
    37  }
    38  
    39  func main() {
    40  
    41  	myRectangle := simpleshape.NewRectangle(4, 5)
    42  	myTriangle := simpleshape.NewTriangle(2, 7)
    43  	shapesSlice := []interface{}{myRectangle, myTriangle}
    44  	for index, shape := range shapesSlice {
    45  		fmt.Printf("Shape in index, %d, of the shapesSlice is a  %T\n", index, shape)
    46  	}
    47  	fmt.Println("\n")
    48  
    49  	aRandomShape := giveMeARandomShape()
    50  	fmt.Printf("The type of aRandomShape is %T\n", aRandomShape)
    51  	switch t := aRandomShape.(type) {
    52  	case *simpleshape.Rectangle:
    53  		fmt.Println("I got back a rectangle with an area equal to ", t.Area())
    54  	case *simpleshape.Triangle:
    55  		fmt.Println("I got back a triangle with an area equal to ", t.Area())
    56  	default:
    57  		fmt.Println("I don't recognize what I got back!")
    58  	}
    59  
    60  }