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 +}