Deeper into Go

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

 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值