Skip to content

Commit f24a6e2

Browse files
committed
20220331
1 parent 7c80431 commit f24a6e2

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
4242
[第14章 扩展与复用](https://github.com/java-aodeng/golang-examples/blob/master/go-14/extension_test.go)
4343

44-
第15章 不一样的接口类型,一样的多态
44+
[第15章 不一样的接口类型,一样的多态](https://github.com/java-aodeng/golang-examples/blob/master/go-15/empty_interface_test.go)
4545

4646
第16章 编写好的错误处理
4747

go-15/empty_interface_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package go_15
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
//go语言的空接口与断言
9+
//1.go语言的空接口可以表示任何类型,
10+
//2.通过断言来将空接口转换为制定类型
11+
//如:v,ok :=p.(int) //ok=true时为转换成功
12+
func DoSomething(p interface{}) {
13+
switch v := p.(type) {
14+
case int:
15+
fmt.Print("Integer类型的", v)
16+
case string:
17+
fmt.Print("String类型的", v)
18+
default:
19+
fmt.Print("未知类型的")
20+
}
21+
}
22+
23+
//这里主要是体会一下go语言的多态 与其他语言的区别
24+
func TestEmptyInterfaceAssertion(t *testing.T) {
25+
DoSomething(1)
26+
fmt.Print("\n")
27+
DoSomething("1")
28+
}
29+
30+
//运行结果
31+
//=== RUN TestEmptyInterfaceAssertion
32+
//Integer类型的1
33+
//String类型的1--- PASS: TestEmptyInterfaceAssertion ( 0.00s)
34+
//PASS

0 commit comments

Comments
 (0)