Go Tutorial Part 7 Type
Contents
1 Introduction
- Go is not an object oriented language
- But we can define new types based on the existing types by using the keyword
type
2 main.go
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"
}
3 deck.go
package main
import "fmt"
type deck []string
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
4 Dive Deep type deck []string
type
: keyword to start defining a new typedeck
: this will be the name of this type[]string
: this newdeck
type will extend from inbuilt slice of type string. thus it will have all stuff that a slice of string has
4 Dive Deep receiver func (d deck) print()
- All variables of type
deck
will have access to theprint
method deck
tells that the method will be called on deck type- d is the instance of the type deck that the function will be working on
- it is recommended to use the first 1 or 2 letters of the type as the instance variable
5 Defining return type
type laptopSize float64
func (this laptopSize) getSizeOfLaptop() laptopSize {
return this
}
laptopSize
defines the return type