day9接口 类型断言

master
独孤伶俜 2022-12-18 21:10:53 +08:00
parent 07d6217fa6
commit 907c9622a6
1 changed files with 31 additions and 0 deletions

View File

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