- 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"
}
|
package main
import "fmt"
type deck []string
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
|
type: keyword to start defining a new typedeck: this will be the name of this type[]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
- All variables of type
deck will have access to the print 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
type laptopSize float64
func (this laptopSize) getSizeOfLaptop() laptopSize {
return this
}
|
laptopSize defines the return type