day9接口 类型断言
							parent
							
								
									07d6217fa6
								
							
						
					
					
						commit
						907c9622a6
					
				|  | @ -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
 | ||||
| } | ||||
		Loading…
	
		Reference in New Issue