From 907c9622a694c56211bad5b09e3d8d0e57cb3332 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8B=AC=E5=AD=A4=E4=BC=B6=E4=BF=9C?= <1184662350@qq.com> Date: Sun, 18 Dec 2022 21:10:53 +0800 Subject: [PATCH] =?UTF-8?q?day9=E6=8E=A5=E5=8F=A3=20=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/study/day9Interface/TypeAssertions.go | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/study/day9Interface/TypeAssertions.go diff --git a/src/study/day9Interface/TypeAssertions.go b/src/study/day9Interface/TypeAssertions.go new file mode 100644 index 0000000..a30ffbf --- /dev/null +++ b/src/study/day9Interface/TypeAssertions.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "io" + "os" +) + +func main() { + // 类型断言 + + var w io.Writer + w = os.Stdout + f := w.(*os.File) // success: f == os.Stdout + //c := w.(*bytes.Buffer) // panic: interface holds *os.File, not *bytes.Buffer + fmt.Println(f) + rw := w.(io.ReadWriter) + w = rw + fmt.Printf("(%T, %[1]v)\n", w) + // 被断言的接口值的动态类型不能是nil,否则会引发panic + w = nil + // panic: interface conversion: interface {} is nil, not io.ReadWriter + //rw = w.(io.ReadWriter) / + fmt.Printf("(%T, %[1]v)\n", w) + + // 判断断言是否成功可以使用comma-ok断言 + w = os.Stdout + f, ok := w.(*os.File) // success: f == os.Stdout, ok == true + fmt.Println(ok) + f.WriteString("hello, world") // 向控制台输出hello, world +}