OO Approach vs Go approach



Custom Type Declaration

Functions with Receivers
main.go
package main
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"
}
package main
import "fmt"
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
}
PS E:\software\golang\goprojects\goproject1\cards> ls
Directory: E:\software\golang\goprojects\goproject1\cards
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/11/2023 6:49 AM 100 deck.go
-a---- 1/11/2023 6:49 AM 260 main.go
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
0 Ace of Diamonds
1 Five of Diamonds
2 Six of Spades
PS E:\software\golang\goprojects\goproject1\cards>
same as below
package main
func main() {
cards := deck{"Ace of Diamonds", newCard()}
cards = append(cards, "Six of Spades")
// for i, card := range cards {
// fmt.Println(i, card)
// }
cards.print()
}
func newCard() string {
return "Five of Diamonds"
}
package main
import "fmt"
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
0 Ace of Diamonds
1 Five of Diamonds
2 Six of Spades
PS E:\software\golang\goprojects\goproject1\cards>


Test your knowleges for Functions with Receivers




Creating a New Deck


main.go
package main
func main() {
cards := newDeck()
cards.print()
}
deck.go
package main
import "fmt"
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
0 Ace of Spades
1 Two of Spades
2 Three of Spades
3 Four of Spades
4 Ace of Diamonds
5 Two of Diamonds
6 Three of Diamonds
7 Four of Diamonds
8 Ace of Hearts
9 Two of Hearts
10 Three of Hearts
11 Four of Hearts
12 Ace of Clubs
13 Two of Clubs
14 Three of Clubs
15 Four of Clubs
PS E:\software\golang\goprojects\goproject1\cards>
Slice Range Syntax




Multiple Return Values
main.go
package main
func main() {
cards := newDeck()
hand, remainingCards := deal(cards, 5)
hand.print()
remainingCards.print()
}
deck.go
package main
import "fmt"
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
0 Ace of Spades
1 Two of Spades
2 Three of Spades
3 Four of Spades
4 Ace of Diamonds
0 Two of Diamonds
1 Three of Diamonds
2 Four of Diamonds
3 Ace of Hearts
4 Two of Hearts
5 Three of Hearts
6 Four of Hearts
7 Ace of Clubs
8 Two of Clubs
9 Three of Clubs
10 Four of Clubs
PS E:\software\golang\goprojects\goproject1\cards>
Test Your Knowledge: Multiple Return Values
Question 1:
In the following code snippet, what will the value and type of 'title' and 'pages' be?

Question 2:
What will the following program log out?

Question 3:
What will the following program log out?
Question 4:
Which of the following best explains the describe function listed below?


Byte Slices



main.go
package main
import "fmt"
func main() {
cards := newDeck()
fmt.Println(cards.toString())
}
deck.go
package main
import (
"fmt"
"strings"
)
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
Results:
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
Ace of Spades,Two of Spades,Three of Spades,Four of Spades,Ace of Diamonds,Two of Diamonds,Three of Diamonds,Four of Diamonds,Ace of Hearts,Two of Hearts,Three of Hearts,Four of Hearts,Ace of Clubs,Two of Clubs,Three of Clubs,Four of Clubs
PS E:\software\golang\goprojects\goproject1\cards>
Saving Data to the Hard Drive
main.go
package main
func main() {
cards := newDeck()
cards.saveToFile("my_cards")
}
deck.go
package main
import (
"fmt"
"io/ioutil"
"strings"
)
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
func (d deck) saveToFile(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString()), 0666)
}



Suffling a Deck


main.go
package main
func main() {
cards := newDeck()
cards.shuffle()
cards.print()
}
Deck.go
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
)
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
func (d deck) saveToFile(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString()), 0666)
}
func newDeckFromFile(filename string) deck {
bs, err := ioutil.ReadFile(filename)
if err != nil {
// Option #1 - log the error and return a call to newDeck()
// option #2 - log the error and entirely quit the program
fmt.Println("Error:", err)
os.Exit(1)
}
s := strings.Split(string(bs), ",") // Ace of Spades, Two of Spades, Three of Spades,
return deck(s)
}
func (d deck) shuffle() {
for i := range d {
newPosition := rand.Intn(len(d) - 1)
d[i], d[newPosition] = d[newPosition], d[i]
}
}
PS E:\software\golang\goprojects\goproject1\cards> go run main.go deck.go
0 Two of Hearts
1 Ace of Spades
2 Three of Spades
3 Two of Diamonds
4 Ace of Clubs
5 Four of Diamonds
6 Three of Hearts
7 Three of Clubs
8 Ace of Diamonds
9 Four of Hearts
10 Four of Spades
11 Ace of Hearts
12 Two of Spades
13 Two of Clubs
14 Four of Clubs
15 Three of Diamonds
PS E:\software\golang\goprojects\goproject1\cards>
Random Number Generation

package main
func main() {
cards := newDeck()
cards.shuffle()
cards.print()
}
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
func (d deck) saveToFile(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString()), 0666)
}
func newDeckFromFile(filename string) deck {
bs, err := ioutil.ReadFile(filename)
if err != nil {
// Option #1 - log the error and return a call to newDeck()
// option #2 - log the error and entirely quit the program
fmt.Println("Error:", err)
os.Exit(1)
}
s := strings.Split(string(bs), ",") // Ace of Spades, Two of Spades, Three of Spades,
return deck(s)
}
func (d deck) shuffle() {
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range d {
newPosition := r.Intn(len(d) - 1)
d[i], d[newPosition] = d[newPosition], d[i]
}
}
Writing a useful test




本文展示了Go语言中如何创建自定义类型(如卡片deck),使用函数接收者实现方法,处理切片操作,包括添加卡片、打印、洗牌以及保存和加载卡片数据到文件。此外,还涵盖了多值返回功能,用于发牌和分割牌堆,并探讨了随机数生成在洗牌算法中的作用。
239

被折叠的 条评论
为什么被折叠?



