
package main import ( "io" "net/http" "net/rpc" "net/rpc/jsonrpc" ) type dd interface{} func main() { // rpc.RegisterName("HelloService", new(HelloService)) http.HandleFunc("/jsonrpc", func(w http.ResponseWriter, r *http.Request) { var conn io.ReadWriteCloser = struct { io.Writer io.ReadCloser }{ ReadCloser: r.Body, // 这里为什么不是 io.ReadCloser 这是一个 go 的语法特性,还是根据一个特性引申出的另一个特性? 叫什么? 谢谢 Writer: w, // dd: 3, } rpc.ServeRequest(jsonrpc.NewServerCodec(conn)) }) http.ListenAndServe(":1234", nil) } 问题在上端代码的注释中.提前表示感谢.
1 tikazyq 2020 年 7 月 22 日 用匿名 struct 感觉为啥这么别扭 |
3 Reficul 2020 年 7 月 23 日 结构体嵌套了匿名结构 /接口的时候,引用起来就是类型名。 |
4 CoolSpring 2020 年 7 月 23 日 via Android Embedding? https://golang.org/doc/effective_go.html#embedding "If we need to refer to an embedded field directly, the type name of the field, ignoring the package qualifier, serves as a field name" |
5 reus 2020 年 7 月 23 日 这类问题,全都在语言规范里写了的 https://golang.org/ref/spec#Struct_types A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name. 这里说了字段名是 unqualified type name,也就是不带 io. |
6 heimeil 2020 年 7 月 23 日 定义 struct 只指定类型不指定字段名,默认就会用类型名称作为字段名,不包含包名 package main import ( "fmt" "io" "reflect" ) func main() { type T struct { Foo string io.ReadCloser } s := reflect.ValueOf(&T{}).Elem() for i := 0; i < s.NumField(); i++ { fmt.Printf("%d: %s\n", i, s.Type().Field(i).Name) } // 0: Foo // 1: ReadCloser } 定义 struct 是定义类型,需要明确指定包名,实例化 struct 是指定字段名 |
7 byzf 2020 年 7 月 23 日 建议过一遍入门教程. |