Golang那些违背直觉的编程陷阱

2024-04-22 06:20

本文主要是介绍Golang那些违背直觉的编程陷阱,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

知识点1:切片拷贝之后都是同一个元素

知识点2:方法集合决定接口实现,类型方法集合是接口方法集合的超集则认定为实现接口,否则未实现接口


切片拷贝之后都是同一个元素
package mainimport ("encoding/json""fmt"
)func arr1() {var nn []intfor i := 0; i < 5; i++ {nn = append(nn, i)}marshal, _ := json.Marshal(nn)// [0,1,2,3,4]fmt.Println(string(marshal))
}func arr2() {var nn []*intfor i := 0; i < 5; i++ {// 出错原因:每次都是i的地址,i的地址始终是一个,所以最终数组元素是5// 解决方法,每次新生命一个变量,之后使用每次新分配的变量进行赋值。参见arr3nn = append(nn, &i)}//[5,5,5,5,5]marshal, _ := json.Marshal(nn)fmt.Println(string(marshal))
}func arr3() {var nn []*intfor i := 0; i < 5; i++ {// s := inn = append(nn, &s)}marshal, _ := json.Marshal(nn)//[0,1,2,3,4]fmt.Println(string(marshal))
}func main() {arr1()arr2()arr3()
}

主要看一下arr2与arr3函数即可知晓,很好理解却又很容易疏忽。接下来看一个类似问题的变种,跟struct方法有关系示例:

package mainimport ("fmt""time"
)type field struct {name string
}func (p *field) print() {fmt.Println(p.name)
}func main() {data1 := []*field{{"one"}, {"two"}, {"three"}}for _, v := range data1 {go v.print()}data2 := []field{{"four"}, {"five"}, {"six"}}for _, v := range data2 {go v.print()}time.Sleep(3 * time.Second)
}

| 这个代码执行输出结果:

看到结果是不是很意外,为什么有3个six呢?接下来分下一下:由于field的print方法是指针类型,所以data2每次在调用print方法时都是v指向的内存对象,这个对象最后一次赋值是six,所以输出的是3个six(其实此处存在不确定性,main协程与子协程的调度顺序,如果每次调度main协程之后立马就去调度子协程可能结果就是正确的了)。

那怎么修复问题呢?

方法1:

将filed的print方法的接受者修改为值类型,这样每次调用时都会拷贝一个副本进行调用,就会背面这个问题了,具体如下:

func (p field) print() {fmt.Println(p.name)
}

方法2:

每次调用时重新声明一个变量进行调用,这个底层原理也是拷贝一个副本进行调用,具体修改如下:

package mainimport ("fmt""time"
)type field struct {name string
}func (p *field) print() {fmt.Println(p.name)
}func main() {data1 := []*field{{"one"}, {"two"}, {"three"}}for _, v := range data1 {go v.print()}data2 := []field{{"four"}, {"five"}, {"six"}}for _, v := range data2 {replica := v// 此处每次都是重新分配一个内存存储v的副本go replica.print()}time.Sleep(3 * time.Second)
}
方法集合决定接口实现,类型方法集合是接口方法集合的超集则认定为实现接口,否则未实现接口
package mainimport ("fmt""reflect"
)type Interface interface {M1()M2()
}type T struct{}func (t T) M1()  {}
func (t *T) M2() {}func DumpMethodSet(i interface{}) {v := reflect.TypeOf(i)elemTyp := v.Elem()n := elemTyp.NumMethod()if n == 0 {fmt.Printf("%s's method set is empty!\n", elemTyp)return}fmt.Printf("%s's method set:\n", elemTyp)for j := 0; j < n; j++ {fmt.Println("-", elemTyp.Method(j).Name)}fmt.Printf("\n")
}
func main() {var t Tvar pt *Tvar i Interface//Cannot use 't' (type T) as type Interface//Type does not implement 'Interface' as 'M2' method has a pointer receiver// 言外之意就是类型T没有实现接口的M2方法i = ti = pt
}

此处主要需要了解Go方法集合规范是什么才能更好解释问题。如下工具方法可以用于查看类型的方法集合,具体代码如下:

func DumpMethodSet(i interface{}) {v := reflect.TypeOf(i)elemTyp := v.Elem()n := elemTyp.NumMethod()if n == 0 {fmt.Printf("%s's method set is empty!\n", elemTyp)return}fmt.Printf("%s's method set:\n", elemTyp)for j := 0; j < n; j++ {fmt.Println("-", elemTyp.Method(j).Name)}fmt.Printf("\n")
}

调用:

var t T
var pt *T
DumpMethodSet(&t)
DumpMethodSet(&pt)
DumpMethodSet((*Interface)(nil))

输出:

因为T类型的方法集合只有M1,所以导致上面将T类型实例赋值给接口类型会报错。

重点:Golang方法集合规范

1. 对于非接口类型的自定义类型T,其方法集合由所有receiver为T类型的方法组成;

2. 而类型*T的方法集合则包含所有receiver为T和*T类型的方法。也正因为如此,pt才能成功赋值给Interface类型变量。

特别提示:在进行组合时候,内嵌的是指针或值类型的结构体所以涉及引入的方法集是不一样的,也遵循上面规范。一般来说内嵌指针的方法集大于等于值得方法集。参见代码:

package mainimport "51788.net/golang-day01/dump_method_set"//main.T1's method set:
//- T1M1
//- T1M2//*main.T1's method set:
//- PT1M3
//- T1M1
//- T1M2
type T1 struct{}func (T1) T1M1()   { println("T1's M1") }
func (T1) T1M2()   { println("T1's M2") }
func (*T1) PT1M3() { println("PT1's M3") }//main.T2's method set:
//- T2M1
//- T2M2
//
//*main.T2's method set:
//- PT2M3
//- T2M1
//- T2M2
type T2 struct{}func (T2) T2M1()   { println("T2's M1") }
func (T2) T2M2()   { println("T2's M2") }
func (*T2) PT2M3() { println("PT2's M3") }//main.T's method set:
//- PT2M3
//- T1M1
//- T1M2
//- T2M1
//- T2M2
//
//*main.T's method set:
//- PT1M3
//- PT2M3
//- T1M1
//- T1M2
//- T2M1
//- T2M2
type T struct {T1*T2
}func main() {t := T{T1: T1{},T2: &T2{},}pt := &tvar t1 T1var pt1 *T1dump_method_set.DumpMethodSet(&t1)dump_method_set.DumpMethodSet(&pt1)var t2 T2var pt2 *T2dump_method_set.DumpMethodSet(&t2)dump_method_set.DumpMethodSet(&pt2)dump_method_set.DumpMethodSet(&t)dump_method_set.DumpMethodSet(&pt)
}

结论:

  • T类型的方法集合 = T1的方法集合 + *T2的方法集合;
  • *T类型的方法集合 = *T1的方法集合 + *T2的方法集合。
接口方法覆盖
package mainimport "51788.net/golang-day01/dump_method_set"type Interface1 interface {M1()
}type Interface2 interface {M1()M2()
}type Interface3 interface {Interface1Interface2 // Go 1.14之前版本报错:duplicate method M1
}type Interface4 interface {Interface2M2() // Go 1.14之前版本报错:duplicate method M2
}func main() {dump_method_set.DumpMethodSet((*Interface3)(nil))
}

在golang1.14版本之后允许接口中相同方法的覆盖。

类型里面内嵌多个接口,多个接口方法集合存在交集

当多个接口方法存在交集时,交集方法必须在类型上进行显示实现,否则调用交集方法时会报错。(当然如果不显示实现,而且后续不调用交集方法的话也不会报错。如果使用交集方法就要一定在类型上实现交集方法)。

示例1:

package mainimport "fmt"type IRun1 interface {M1()M2()
}type IRun2 interface {M2()M3()
}type IRun1Impl struct{}func (IRun1Impl) M1() {fmt.Println(" (IRun1Impl) M1()")
}func (IRun1Impl) M2() {fmt.Println(" (IRun1Impl) M2()")
}type IRun2Impl struct{}func (IRun2Impl) M2() {fmt.Println(" (IRun2Impl) M2()")
}func (IRun2Impl) M3() {fmt.Println(" (IRun2Impl) M3()")
}type TRun struct {IRun1IRun2
}func (e TRun) M1() {fmt.Println("t m1")
}// 一定在类型上实现交集方法
func (e TRun) M2() {fmt.Println("t m2")
}func main() {e := TRun{IRun1: &IRun1Impl{},IRun2: &IRun2Impl{},}e.M1()e.M2()e.M3()//	输出://t m1//t m2// (IRun2Impl) M3()
}

示例2:

package mainimport "fmt"type IRun1 interface {M1()M2()
}type IRun2 interface {M2()M3()
}type IRun1Impl struct{}func (IRun1Impl) M1() {fmt.Println(" (IRun1Impl) M1()")
}func (IRun1Impl) M2() {fmt.Println(" (IRun1Impl) M2()")
}type IRun2Impl struct{}func (IRun2Impl) M2() {fmt.Println(" (IRun2Impl) M2()")
}func (IRun2Impl) M3() {fmt.Println(" (IRun2Impl) M3()")
}type TRun struct {IRun1IRun2
}func (e TRun) M1() {fmt.Println("t m1")
}func main() {e := TRun{IRun1: &IRun1Impl{},IRun2: &IRun2Impl{},}e.M1()// 不在类型上声明M2方法,虽然两个接口都有声明M2方法,但是也会报错:// 编译器报错:Ambiguous reference 'M2'e.M2()e.M3()}

示例三:

package mainimport "fmt"type IRun1 interface {M1()M2()
}type IRun2 interface {M2()M3()
}type IRun1Impl struct{}func (IRun1Impl) M1() {fmt.Println(" (IRun1Impl) M1()")
}func (IRun1Impl) M2() {fmt.Println(" (IRun1Impl) M2()")
}type IRun2Impl struct{}func (IRun2Impl) M2() {fmt.Println(" (IRun2Impl) M2()")
}func (IRun2Impl) M3() {fmt.Println(" (IRun2Impl) M3()")
}type TRun struct {IRun1IRun2
}func (e TRun) M1() {fmt.Println("t m1")
}func main() {e := TRun{IRun1: &IRun1Impl{},IRun2: &IRun2Impl{},}e.M1()// 虽然没有在类型上声明M2方法,但是不调用M2方法的话也不会存在编译错误// 满足原则:你用你写,不用不写(u can u up)//e.M2()e.M3()
}

小提示:现实中应该避免这种复杂编程,显然无疑的提高了问题复杂度,并无显著收益。

类型里面内嵌接口

type InterfaceX interface {M1()M2()
}type TS struct {InterfaceX
}func (TS) M3() {}

类型TS内嵌接口InterfaceX是允许的,而且编译器不要求强制必须实现M1与M2方法,这个如果有Java经验的话会很违背经验。但是Golang就是允许的,但是如果你调用未实现的方法就会报错:

func main() {var t TSt.M1()
}

查看一下方法集合:

func main() {dump_method_set.DumpMethodSet((*InterfaceX)(nil))var t TSvar pt *TSdump_method_set.DumpMethodSet(&t)dump_method_set.DumpMethodSet(&pt)
}

输出:

类型中内嵌接口,命名冲突的方法调用优先级
package maintype Interface interface {M1()M2()
}type T struct {Interface
}// 类型T上实现了接口M1方法,但是类型T未实现M2方法
func (T) M1() {println("T's M1")
}type S struct{}func (S) M1() {println("S's M1")
}
func (S) M2() {println("S's M2")
}func main() {var t = T{Interface: S{},}// 因为类型实现了M1方法,所以直接调用M1的方法t.M1()// 因为接口类型没有实现M2方法,所以调用会从内嵌的接口上寻找方法t.M2()
}

这篇关于Golang那些违背直觉的编程陷阱的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/925007

相关文章

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

golang 日志log与logrus示例详解

《golang日志log与logrus示例详解》log是Go语言标准库中一个简单的日志库,本文给大家介绍golang日志log与logrus示例详解,感兴趣的朋友一起看看吧... 目录一、Go 标准库 log 详解1. 功能特点2. 常用函数3. 示例代码4. 优势和局限二、第三方库 logrus 详解1.

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

Golang中拼接字符串的6种方式性能对比

《Golang中拼接字符串的6种方式性能对比》golang的string类型是不可修改的,对于拼接字符串来说,本质上还是创建一个新的对象将数据放进去,主要有6种拼接方式,下面小编就来为大家详细讲讲吧... 目录拼接方式介绍性能对比测试代码测试结果源码分析golang的string类型是不可修改的,对于拼接字

如何通过Golang的container/list实现LRU缓存算法

《如何通过Golang的container/list实现LRU缓存算法》文章介绍了Go语言中container/list包实现的双向链表,并探讨了如何使用链表实现LRU缓存,LRU缓存通过维护一个双向... 目录力扣:146. LRU 缓存主要结构 List 和 Element常用方法1. 初始化链表2.

Golang基于内存的键值存储缓存库go-cache

《Golang基于内存的键值存储缓存库go-cache》go-cache是一个内存中的key:valuestore/cache库,适用于单机应用程序,本文主要介绍了Golang基于内存的键值存储缓存库... 目录文档安装方法示例1示例2使用注意点优点缺点go-cache 和 Redis 缓存对比1)功能特性

Golang中map缩容的实现

《Golang中map缩容的实现》本文主要介绍了Go语言中map的扩缩容机制,包括grow和hashGrow方法的处理,具有一定的参考价值,感兴趣的可以了解一下... 目录基本分析带来的隐患为什么不支持缩容基本分析在 Go 底层源码 src/runtime/map.go 中,扩缩容的处理方法是 grow

golang获取prometheus数据(prometheus/client_golang包)

《golang获取prometheus数据(prometheus/client_golang包)》本文主要介绍了使用Go语言的prometheus/client_golang包来获取Prometheu... 目录1. 创建链接1.1 语法1.2 完整示例2. 简单查询2.1 语法2.2 完整示例3. 范围值

golang panic 函数用法示例详解

《golangpanic函数用法示例详解》在Go语言中,panic用于触发不可恢复的错误,终止函数执行并逐层向上触发defer,最终若未被recover捕获,程序会崩溃,recover用于在def... 目录1. panic 的作用2. 基本用法3. recover 的使用规则4. 错误处理建议5. 常见错