Go Tutorial Part 7 Type

Contents
  1. Go is not an object oriented language
  2. But we can define new types based on the existing types by using the keyword type
package main

func main() {
	cards := deck{"Ace of Diamond", newCard()}

	cards = append(cards, "Six of Spades")

	cards.print()

}

func newCard() string {
	return "Five of Diamonds"
}

package main

import "fmt"

type deck []string

func (d deck) print() {
	for i, card := range d {
		fmt.Println(i, card)
	}
}

  1. type: keyword to start defining a new type
  2. deck: this will be the name of this type
  3. []string: this new deck type will extend from inbuilt slice of type string. thus it will have all stuff that a slice of string has
  1. All variables of type deck will have access to the print method
  2. deck tells that the method will be called on deck type
  3. d is the instance of the type deck that the function will be working on
  4. it is recommended to use the first 1 or 2 letters of the type as the instance variable
type laptopSize float64
  
func (this laptopSize) getSizeOfLaptop() laptopSize {
    return this
}

laptopSize defines the return type