17 OO Approach vs GO Approach
面向对象
image.png
type
receiver
17例子
image.png
type
// deck.go
package main
// create a new type of 'deck'
// which is a slice of strings
type deck []string // 有点像声明类
}
// main.go
package main
import "fmt"
func main(){
cards := deck{"Ace of Diamonds", newCard()}
cards = append(cards, "six of spades")
for i, card := range cards{
fmt.Println(i, card)
}
}
func newCard() string{
return "Five of Diamonds"
}
receiver 接收器
// deck.go
package main
// create a new type of 'deck'
// which is a slice of strings
type deck []string // 有点像声明类
// any variable of type "deck" now gets access to the "print" method
// 接收器为我们创建的变量设置方法
func (d deck) print(){ // 定义一个接收器,表示任意deck类型可以使用print方法
for i, card := range d { // 此处d类似于python中的self
fmt.Println(i, card)
}
}
// type像声明类,receiver像类实例的方法
// main.go
package main
import "fmt"
func main(){
cards := deck{"Ace of Diamonds", newCard()}
cards = append(cards, "six of spades")
cards.print() // 接收器使用处
}
func newCard() string{
return "Five of Diamonds"
}
image.png
21 Slice Range Syntax
切片,左闭右开
[0:2] //即0,1
22 multiple return values
func deal(d deck, handSize int)(deck, deck){
return d[:handSize], d[handSize:]
}
deal("aaaaa", 1)
23 type convert
i mage.png
package main
func main(){
greeting := "Hi there!"
fmt.Println([]byte(greeting))
}
> [76 88 99 ]
24 Deck to String
// deck.go
package main
import (
"fmt"
"strings"
)
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
//main.go
import "fmt"
func main() {
cards := newDeck()
fmt.Println(cards.toString())
}