方法一: if sw, ok := w.(stringWriter); ok { return sw.WriteString(s) } 根据ok的值判断断言是否成功。 方法二: switch a.(type) { case int64: if i, ok := a.(int64); ok { return int(i),nil…
一、make make 只能为 slice、map或 channel 类型分配内存并初始化,同时返回一个有初始值的 slice、map 或 channel 类型引用,不是指针。 通过下表再来看 make 的具体应用: Call Type T Result make(T, n) slice slice of type T with length n…
go中对文件和目录的操作主要集中在os包中,下面对go中用到的对文件和目录的操作,做一个总结笔记。在go中的文件和目录涉及到两种类型,一个是 type File struct,另一个是type Fileinfo interface,来看下这两种类型的定义: 一、 type File struct 的定义 type File struct { *file // os specific } type file struct { fd int name…
Go语言的并发和并行 不知道你有没有注意到一个现象,还是这段代码,如果我跑在两个goroutines里面的话: var quit chan int = make(chan int) func loop() { for i := 0; i < 10; i++ { fmt.Printf("%d ", i) }…
几天前,我写了一篇文章来说明golang中channel的使用规范。在reddit和HN,那篇文章收到了很多赞同,但是我也收到了下面几个关于Go channel设计和规范的批评: 在不能更改channel状态的情况下,没有简单普遍的方式来检查channel是否已经关闭了 关闭已经关闭的channel会导致panic,所以在closer(关闭者)不知道channel是否已经关闭的情况下去关闭channel是很危险的 发送值到已经关闭的channel会导致panic,所以如果sender(发送者)在不知道channel是否已经关闭的情况下去向channel发送值是很危险的 那些批评看起来都很有道理(实际上并没有)。是的,没有一个内置函数可以检查一个channel是否已经关闭。如果你能确定不会向channel发送任何值,那么也确实需要一个简单的方法来检查channel是否已经关闭: package main import "fmt" type T int func IsClosed(ch <-chan T) bool { select { case <-ch: return…