pair和reflect
This commit is contained in:
parent
320ca10ac9
commit
b872f182f3
40
bilibili/aceid/struct/pair/test.go
Normal file
40
bilibili/aceid/struct/pair/test.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type Reader interface {
|
||||||
|
ReadBook()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Writer interface {
|
||||||
|
WriteBook()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 具体类型
|
||||||
|
type Book struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Book) ReadBook() {
|
||||||
|
fmt.Println("Read a Book")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Book) WriteBook() {
|
||||||
|
fmt.Println("Write a Book")
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// b: pair<type: Book, value: book{}地址>
|
||||||
|
b := &Book{}
|
||||||
|
|
||||||
|
// r: pair<type: , value: >
|
||||||
|
var r Reader
|
||||||
|
// r: pair<type: Book, value: book{}地址>
|
||||||
|
r = b
|
||||||
|
|
||||||
|
r.ReadBook()
|
||||||
|
|
||||||
|
var w Writer
|
||||||
|
// r: pair<type: Book, value: book{}地址>
|
||||||
|
w = r.(Writer) // 此处的断方为什么会成功?因为w r的具体type是一致的
|
||||||
|
w.WriteBook()
|
||||||
|
}
|
37
bilibili/aceid/struct/reflect/test.go
Normal file
37
bilibili/aceid/struct/reflect/test.go
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var a string
|
||||||
|
// pair<statictype: string, value: "aceld">
|
||||||
|
a = "aceld"
|
||||||
|
|
||||||
|
// pair<type: string, value "aceld">
|
||||||
|
var allType interface{}
|
||||||
|
allType = a
|
||||||
|
str, _ := allType.(string)
|
||||||
|
fmt.Println(str)
|
||||||
|
|
||||||
|
// type: pair<type:*os.File, value: "/dev/tty"文件描述符>
|
||||||
|
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("open file error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// r: pair<type: , value: >
|
||||||
|
var r io.Reader
|
||||||
|
// r: pair<type:*os.File , value:"/dev/tty"文件描述符>
|
||||||
|
r = tty
|
||||||
|
// w: pair<type: , value: >
|
||||||
|
var w io.Writer
|
||||||
|
// w: pair<type:*os.File, value:"/dev/tty"文件描述符>
|
||||||
|
w = r.(io.Writer)
|
||||||
|
w.Write([]byte("HELLO THIS is A TEST!!!\n"))
|
||||||
|
r.(io.Writer).Write([]byte("HELLO THIS is A TEST, too!!!\n"))
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user