Coder Social home page Coder Social logo

polaris1119 / the-golang-standard-library-by-example Goto Github PK

View Code? Open in Web Editor NEW
9.4K 580.0 2.0K 518 KB

Golang标准库。对于程序员而言,标准库与语言本身同样重要,它好比一个百宝箱,能为各种常见的任务提供完美的解决方案。以示例驱动的方式讲解Golang的标准库。

Home Page: https://studygolang.com

Go 97.23% Batchfile 1.29% Shell 1.48%
golang standard-golang-library linux go

the-golang-standard-library-by-example's Issues

3.1.1 数据集合排序

// 如果 i 索引的数据小于 j 索引的数据,返回 true,且不会调用下面的 Swap(),即数据升序排序。
Less(i, j int) bool
i 索引是后面的位置, 正是此时调用 Swap

网络包 net

发现缺少非常重要的网络包 net 的相关用法,比如 net/http 和 net/rpc 等,希望能够及时补充

3.3的例子,编译直接报错

cannot use h (type *IntHeap) as type heap.Interface in argument to heap.Init:
*IntHeap does not implement heap.Interface (wrong type for Pop method)
have Pop(interface {}) interface {}
want Pop() interface {}

cannot use h (type *IntHeap) as type heap.Interface in argument to heap.Push:
*IntHeap does not implement heap.Interface (wrong type for Pop method)
have Pop(interface {}) interface {}
want Pop() interface {}

cannot use h (type *IntHeap) as type heap.Interface in argument to heap.Pop:
*IntHeap does not implement heap.Interface (wrong type for Pop method)
have Pop(interface {}) interface {}
want Pop() interface {}

关于 16.01.md Cond 的例子

package main

import (
    "fmt"
    "sync"
    "time"
)

var locker = new(sync.Mutex)
var cond = sync.NewCond(locker)

func test(x int) {

    cond.L.Lock() // 获取锁
    cond.Wait()   // 等待通知  暂时阻塞
    fmt.Println(x)
    time.Sleep(time.Second * 1)
    cond.L.Unlock() // 释放锁,不释放的话将只会有一次输出
}
func main() {
    for i := 0; i < 40; i++ {
        go test(i)
    }
    fmt.Println("start all")
    cond.Broadcast() //  下发广播给所有等待的goroutine
    time.Sleep(time.Second * 60)
}

我自己在试的时候发现 test 函数的并不能正常打印出结果。有时候没有输出,有时候输出很多。

我想问下这个是不是因为 goroutine 无序执行的原因?

3.3.1 堆这节有个错字

3.3.1 堆这一节的:

内部实现了down和up分别表示对堆中的某个元素向上保证最小堆和向上保证最小堆。

中打错了一个字吧, 应该是:
内部实现了down和up分别表示对堆中的某个元素向下保证最小堆和向上保证最小堆。

chapter01/01.3.md 漏加代码框

var ( name string age int ) n, _ := fmt.Sscan("polaris 28", &name, &age) // 可以将"polaris 28"中的空格换成"\n"试试 // n, _ := fmt.Sscan("polaris\n28", &name, &age) fmt.Println(n, name, age)

Sort should add SliceStable

Hi,

I think about the sort section should have SliceStable

reference

https://golang.org/pkg/sort/#SliceStable

e.g.

family := []struct {
    Name string
    Age  int
}{
    {"Alice", 23},
    {"David", 2},
    {"Eve", 2},
    {"Bob", 25},
}

// Sort by age, keeping original order or equal elements.
sort.SliceStable(family, func(i, j int) bool {
    return family[i].Age < family[j].Age
})
fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

图片挂了?

Git 下来之后,在 typro中打开,所有的图片都下载失败

关于附源码的一点建议

因为Go目前还处于积极开发之中,所以源码还是会变,所以建议如果是贴Golang源码的话,最好附注一下版本。

2.1.6 字符串 JOIN 函数, 实现方法已经修改

关于join函数的说明, 可能需要修改

标准库的实现没有用 bytes 包,当然也不会简单的通过 + 号连接字符串

目前查看标准库实现方式是使用了 += 字符串连接操作的.

func Join(a []string, sep string) string {
	switch len(a) {
	case 0:
		return ""
	case 1:
		return a[0]
	case 2:
		// Special case for common small values.
		// Remove if golang.org/issue/6714 is fixed
		return a[0] + sep + a[1]
	case 3:
		// Special case for common small values.
		// Remove if golang.org/issue/6714 is fixed
		return a[0] + sep + a[1] + sep + a[2]
	}
        ...
$ go version
go version go1.10 windows/amd64

该版本也没有引入 bytes 包. 但直接使用了 += 连接符

log 包

关于 log的不能访问了

第七章说连接池工作原理的时候重试次数不是2吗

如果某个连接有问题(broken connection),database/sql 内部会进行最多 10 次 的重试,从连接池中获取或新开一个连接来服务,因此,你的代码中不需要重试的逻辑。
我看代码里const maxBadConnRetries = 2

关于 sync.Cond.Broadcast() 的讨论

package main

import (
    "fmt"
    "sync"
    "time"
)

var locker = new(sync.Mutex)
var cond = sync.NewCond(locker)

func test(x int) {

    cond.L.Lock() // 获取锁
    cond.Wait()   // 等待通知  暂时阻塞
    fmt.Println(x)
    time.Sleep(time.Second * 1)
    cond.L.Unlock() // 释放锁,不释放的话将只会有一次输出
}
func main() {
    for i := 0; i < 40; i++ {
        go test(i)
    }
    fmt.Println("start all")
    cond.Broadcast() //  下发广播给所有等待的goroutine
    time.Sleep(time.Second * 60)
}

上面这个例子是从 chapter16/16.01.md 中 copy 下来,运行后,没有问题(或者说极少数人会遇到问题)
那接下来就做一行代码的修改

fmt.Println("start all") 注释掉

运行后会发现,程序没有输出了,或者说程序已经进入了 sleep 等待退出的状态了。

分析修改后的代码,在 Broadcast 执行时, Wait 操作还没来得及把通知加入 cond 的 notifyList 中,而例子中因为 fmt.Println("start all") 这一微弱的开销,使得 40 个 groutine 中已经有部分或者全部争取到了加入 notifyList 的机会。

顺着这个思路,猜测如果把 loop 次数增加,使得 loop 先执行的 groutine 有机会被加入 notifyList 中,我们修改为 1000、4000、10000等偿试。确实会如我们所料。命令如下:

go run main.go | wc -l

综上所述, 使得本人对 sync.Cond 的应用场景及正确姿势有了一些疑问,希望楼主及大伙一起探究。

unicode章节建议增加汉字range

在unicode package中定义了各种字符的range,比如unicode.Han则代表了所有中文字符的range,还有个方法提供判断一个字符是不是落在某个区间。具体可以参考下面的一个示例。

package main

import (
	"unicode"
	"fmt"
)

func main() {
	fmt.Println(unicode.In('C', unicode.Han))
	fmt.Println(unicode.In('具', unicode.Han))
}

output:
false
true

有一个问题

        sr := strings.NewReader("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
	buf := bufio.NewReaderSize(sr, 0) 
	b := make([]byte, 10)
	fmt.Println(buf.Buffered()) // 
	s, _ := buf.Peek(5)
	s[0], s[1], s[2] = 'a', 'b', 'c'
	fmt.Printf("%d   %q\n", buf.Buffered(), s) 

为啥使用了Peek 后 buf.Buffered()就不是0了。

第一章 1. 1.2 ioutil — 方便的IO操作函数集

1.2. ReadAll 函数
很多时候,我们需要一次性读取 io.Reader 中的数据,通过上一节的讲解,我们知道有很多种实现方式。考虑到读取所有数据的需求比较多,Go 提供了 ReadAll 这个函数,用来从io.Reader 中一次读取所有数据。

func ReadAll(r io.Reader) ([]byte, error)

阅读该函数的源码发现,它是通过 bytes.Buffer 中的 ReadFrom 来实现读取所有数据的。该函数成功调用后会返回 err == nil 而不是 err == EOF。(成功读取完毕应该为 err == io.EOF,这里返回 nil 由于该函数成功期望 err == io.EOF,符合无错误不处理的理念)
这里的ReadAll方法是直接使用了Read方法,而不是ReadFrom,请仔细阅读源码
而且是直接调用io包中的readAll

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.