golang 常见疑惑总结
经常会有一些朋友问go语言的一些问题和疑惑,其实好多问题在官方文档和stackoverflow里都有详细的讲解,只要你肯花时间读一遍官方文档和Effective Go基本上都有找到答案。本文总结一下大家经常问到的一些问题,长期更新。
代码都在github上, 地址 https://github.com/lpxxn/gocommonquestions
new 和make 的区别
简单来说,new(T)用于分配内存,返回指向T类型的一个指针,指针的值为T类型的零值
n1 := new(int)
fmt.Println(n1) // console the address of n1
fmt.Println(*n1 == ) // zero value type T struct {
I int
A string
Next *T
}
n2 := new(T)
fmt.Println(n2)
fmt.Println(n2.I == )
fmt.Println(n2.Next == nil)
fmt.Println(n2.A == "") n3 := new([]int)
fmt.Println(n3)
fmt.Println(*n3 == nil)
make(T) 只能用于slice、map和channel, 返回非零值的T。
m1 := make([]int, )
fmt.Println(m1)
m2 := make(map[int]string)
m2[] = "abcde"
m3 := make(chan int) m4 := make(chan int, )
make 返回的是类型本身,new 返回的是指向类型的指针
相关讲解
https://stackoverflow.com/questions/9320862/why-would-i-make-or-new
https://golang.org/doc/effective_go.html#allocation_new
https://golang.org/ref/spec#The_zero_value
是否需要主动关闭channel
除非你的程序需要等待channel关闭后做一些操作,不用主动去关闭channel。当没有地方在使用这个channel的时候go的垃圾回收系统会自动回收,如果channel里还有值,但是没有地方引用了,也会被回收。
下面的小例子就是在等待channel c1和c2关闭后,再做一些事情。
func main() {
c1 := make(chan int, )
go test1(c1)
for v := range c1 {
fmt.Println(v)
}
fmt.Println("after close c1 do something")
c2 := make(chan bool)
go func() {
time.AfterFunc(time.Second * , func() {
close(c2)
})
}()
_, close := <- c2
if !close {
fmt.Println("after c2 closed do something")
}
fmt.Println("end")
}
func test1(c chan<- int) {
for i := ; i < ; i++ {
c <- i
}
close(c)
}
简单测试垃圾回收channel
func createChan() chan int64{
c := make(chan int64, )
c <-
return c
}
func main() {
RM()
for i := ; i < ; i++ {
c := createChan()
c <-
RM()
runtime.GC()
}
RM()
}
func RM(){
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Println(m.Alloc)
}
相关讲解:https://stackoverflow.com/questions/8593645/is-it-ok-to-leave-a-channel-open
https://groups.google.com/forum/#!msg/golang-nuts/pZwdYRGxCIk/qpbHxRRPJdUJ
https://groups.google.com/forum/#!topic/golang-nuts/KtIyc5lTRJY
Unbuffered channel和buffered channel 区别
buffered channel
c3 := make(chan bool, ) // buffered channel
buffered channel 可以持续的发送数据到channel,直到channel满为至。不用等待是否有接收channel。
如果channel满了,会等待读取channel,当有channel被读取,就会继续发送数据到channel
c3 := make(chan bool, ) // buffered channel
go func() {
for i := ; i < ; i++ {
c3 <- i % ==
}
close(c3)
}()
for v := range c3 {
fmt.Println(v)
}
unbuffered channel
下面这两种声明是一样的
c1 := make(chan bool, ) // unbuffered channel
c2 := make(chan bool) // unbuffered channel
unbuffered channel 的接收channel会一直阻塞,直到有值传给channel, 也可以说发送channel会一直阻塞,至到有接收channel
c1 := make(chan bool, ) // unbuffered channel
c2 := make(chan bool) // unbuffered channel go func() {
c1 <- false
time.Sleep(time.Second * )
c2 <- true
}() fmt.Println(<-c1)
fmt.Println(<-c2)
相关讲解:
https://golang.org/doc/effective_go.html
定义类型和组合类型的区别
定义类型,也可以说是别名和组合类型的区别
有一个Test的结构,NewTest是以Test为类型的一个定义,New2Test和New3Test都是组合类型
type Test struct { N int }
func (m *Test) Name() { fmt.Println("abc")}
// NewTest does not inherit any functions of Test
// can access fields
type NewTest Test
// New2Test is composite type, it inherit all functions of Test
// can access fields
type New2Test struct {
Test
}
// if embedded type is pointer you must initialized it
type New3Test struct {
*Test
}
1.定义类型NewTest 相当于一个新的类型,他不能直接调用Test的方法,但是可以访问Test的字段。如果想调用原类型的方法需要做转换
2.New2Test和New3Test都是组合类型,他俩都可以直接调用Test的方法和访问Test的字段,他俩的不同之处就是一个是值组合一个是指针组合
3.在实例化New3Test的时候需要手动实例化*Test指针
n := NewTest{}
n.N =
// n have no method
// n.Name() // error
v := (*Test)(&n)
v.Name()
v2 := Test(n)
v2.Name()
n2 := New2Test{}
n2.N =
n2.Name()
n3 := New3Test{Test: new(Test)}
// access filed N will panic if you do not initialized *Test
n3.N =
n3.Name()
相关的解答:
https://golang.org/ref/spec#Type_declarations
---
golang 常见疑惑总结的更多相关文章
- golang 常见变成问题01
Golang常见编程问题 --语言简单 func CopyFile (dst, src string) (w int64, err error) { srcFile, err := os.Open ( ...
- Golang 常见设计模式之单例模式
之前我们已经看过了 Golang 常见设计模式中的装饰和选项模式,今天要看的是 Golang 设计模式里最简单的单例模式.单例模式的作用是确保无论对象被实例化多少次,全局都只有一个实例存在.根据这一特 ...
- Golang 常见设计模式之选项模式
熟悉 Python 开发的同学都知道,Python 有默认参数的存在,使得我们在实例化一个对象的时候,可以根据需要来选择性的覆盖某些默认参数,以此来决定如何实例化对象.当一个对象有多个默认参数时,这个 ...
- Golang常见误区(二)
35. 关闭 HTTP 的响应体 使用 HTTP 标准库发起请求.获取响应时,即使你不从响应中读取任何数据或响应为空,都需要手动关闭响应体.新手很容易忘记手动关闭,或者写在了错误的位置: // 请求失 ...
- Linux网络编程系列-常见疑惑
1.并发TCP最大连接数 一个TCP连接有一个四元组唯一标识{local_ip, local_port, remote_ip, remote_port} client端建立连接请求时,通常让系统分配一 ...
- Golang常见误区(一)
1.左大括号一般不能单独一行 在其他大多数语言中,{ 的位置你自行决定.Go 比较特别,遵守分号注入规则(automatic semicolon injection):编译器会在每行代码尾部特定分隔符 ...
- golang常见错误
import import unuse package: error : imported and not used: "os" := = c := 1 // error non- ...
- Java语法基础常见疑惑解答8,16,17,21图片补充
8. 16. 17. 21
- Java语法基础常见疑惑解答
1. 类是java的最小单位,java的程序必须在类中才能运行 2. java函数加不加static有何不同 java中声明为static的方法称为静态方法或类方法.静态方法可以直接调用静态方法,访问 ...
随机推荐
- 【shell点滴】参数变量
参数变量故名思议就是用来操作输入参数的变量,知道用户输入了哪些参数,才可以进行相应的处理. 参数变量 作用 $1,$2- 取第几个参数的意思 $* 取出所有的参数,解析参数的分割符环境变量 IFS 来 ...
- Android开发学习之路--UI之基本布局
上一篇文章中主要介绍了ui的控件,这里就学习下布局吧.android的基本布局在layout下主要如图: 从上图可以看出有FrameLayout(单帧布局),LinearLayout(线性布局),Ta ...
- 统计git代码提交量
以下是我写的一个脚本,可以统计在某个项目中,自己修改代码的行数,包括增加多少行,删除多少行. 可以统计当天,24小时内或全部时间内.使用时需要把代码中的author对应的值换成自己的名字. 代码如下: ...
- SDL2源代码分析1:初始化(SDL_Init())
===================================================== SDL源代码分析系列文章列表: SDL2源代码分析1:初始化(SDL_Init()) SDL ...
- Spark Streaming + Flume整合官网文档阅读及运行示例
1,基于Flume的Push模式(Flume-style Push-based Approach) Flume被用于在Flume agents之间推送数据.在这种方式下,Spark Stre ...
- 【一天一道LeetCode】#98. Validate Binary Search Tree
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- mxGraph进阶(一)mxGraph教程-开发入门指南
mxGraph教程-开发入门指南 概述 mxGraph是一个JS绘图组件适用于需要在网页中设计/编辑Workflow/BPM流程图.图表.网络图和普通图形的Web应用程序.mxgraph下载包中包括用 ...
- libgdx 1.4.1发布
(转载自http://www.libgdx.cn/topic/4/libgdx-1-4-1%E5%8F%91%E5%B8%83) libgdx从未停止进步的脚步.10月10日,libgdx1.4.1发 ...
- APPCORE Routine APIs
Introduction to APPCORE Routine APIs This chapter provides you with specifications for calling many ...
- hive parition的使用,分dynamic和static两种
partition是hive提供的一种机制:用户通过指定一个或多个partition key,决定数据存放方式,进而优化数据的查询 一个表可以指定多个partition key,每个partition ...