Tuesday, September 8, 2020

Golang: Declare a type

 Declare a type.


type typeName struct{

 field1 typeoffield1

 field2 typeoffield2

}


Creating an instance of  type with postion

t:=typeName{field1value,field2value}


Creating an instance of type with field names

t:=typeName{field2: field2value.field1:field1value}




can define methods using a pointer receiver(r *typeName).

The receiver is the implicit first argument to function.

a method is a function associated with a type.


type typeName struct{

 field1 typeoffield1

 field2 typeoffield2

}

func (r *typeName) methodName() returnType{


}

//calling t.methodName()



//triangle.go
package simpleshape

type Triangle struct {
	base   float64
	height float64
}

//serves as a constructor with reference to new Triangle instance.
//Not a method as pointer fn not there.
func NewTriangle(b float64, h float64) *Triangle {
	return &Triangle{base: b, height: h}
}

func (t *Triangle) Area() float64 {
	return (t.base * t.height) / 2
}

//rectangle.go
package simpleshape

type Rectangle struct {
	width  float64
	height float64
}

func NewRectangle(w float64, h float64) *Rectangle {
	return &Rectangle{width: w, height: h}

}

func (r *Rectangle) Area() float64 {
	return r.width * r.height
}



two have similar code in common, create inteface.

Declaring an interface

type InterfaceName interface{
  methodName1() returnType1
  methodName2() returnType2
}

A type implements an interface when it has defined all methods in the method list of an interface.
we can't provide field names, only methods in the interface.



//simpleshape.go
// Package simpleshape is a simple interface for representing geometric shapes.
package simpleshape

// The Shape type represents a geometric shape.
type Shape interface {
	Area() float64
}

// Calculates the area of a shape. The area calculation is based on the type of shape s.
func ShapeArea(s Shape) float64 {

	return s.Area()

}

//shapedemo.go
// A demonstration program using the simpleshape package.
package main

import (
	"fmt"

	"github.com/EngineerKamesh/gofullstack/volume1/section3/simpleshape"
)

func main() {

	r := simpleshape.NewRectangle(9, 6)
	t := simpleshape.NewTriangle(3, 6)

	fmt.Println("Area of myRectangle: ", simpleshape.ShapeArea(r))
	fmt.Println("Area of myTriangle: ", simpleshape.ShapeArea(t))

}

no subclasses concept in go.
We can use pieces of an implemenation by embedding types,either within a struct or interface.

type Reader interface{
 Read(p []byte)(n int,err error)
}

type Writer interface{
 Write(p []byte)(n int,err error)
}

type ReadWriter interface{
 Reader
 Writer
}

The Empty Interface
Every type in Go implements the empty interface.
interface{}

Some use cases:
--
-A function that returns a value of interface{} can return any type.
-We can store heterogeneous values in an array, slice, or map using the interface{} type.



//emptyinterfacedemo.go
// An example of an empty interface, and some useful things we can do with it.
package main

import (
	"fmt"
	"math/rand"
	"time"

	"github.com/EngineerKamesh/gofullstack/volume1/section3/simpleshape"
)

func giveMeARandomShape() interface{} {

	var shape interface{}
	var randomShapesSlice []interface{} = make([]interface{}, 2)

	// Seed the random generator
	s := rand.NewSource(time.Now().UnixNano())
	r := rand.New(s)

	// Pick a random number, either 1 or 0
	randomNumber := r.Intn(2)
	fmt.Println("Random Number: ", randomNumber)

	// Let's make a new rectangle
	rectangle := simpleshape.NewRectangle(3, 6)

	// Let's make a new triangle
	triangle := simpleshape.NewTriangle(9, 18)

	// Let's store the shapes into a slice data structure
	randomShapesSlice[0] = rectangle
	randomShapesSlice[1] = triangle
	shape = randomShapesSlice[randomNumber]

	return shape
}

func main() {

	myRectangle := simpleshape.NewRectangle(4, 5)
	myTriangle := simpleshape.NewTriangle(2, 7)
	shapesSlice := []interface{}{myRectangle, myTriangle}
	for index, shape := range shapesSlice {
		fmt.Printf("Shape in index, %d, of the shapesSlice is a  %T\n", index, shape)
	}
	fmt.Println("\n")

	aRandomShape := giveMeARandomShape()
	fmt.Printf("The type of aRandomShape is %T\n", aRandomShape)
	switch t := aRandomShape.(type) {
	case *simpleshape.Rectangle:
		fmt.Println("I got back a rectangle with an area equal to ", t.Area())
	case *simpleshape.Triangle:
		fmt.Println("I got back a triangle with an area equal to ", t.Area())
	default:
		fmt.Println("I don't recognize what I got back!")
	}

}

No comments:

Post a Comment