请教一个 Go 的语法问题

2020-07-22 23:22:17 +08:00
 chaleaoch
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)
}


问题在上端代码的注释中.提前表示感谢.

1950 次点击
所在节点    Go 编程语言
9 条回复
tikazyq
2020-07-22 23:28:46 +08:00
用匿名 struct 感觉为啥这么别扭
chaleaoch
2020-07-22 23:32:18 +08:00
@tikazyq 我知道这是匿名, 匿名没问题,不过为什么"io/"不见连.
Reficul
2020-07-23 00:13:00 +08:00
结构体嵌套了匿名结构 /接口的时候,引用起来就是类型名。
CoolSpring
2020-07-23 00:22:04 +08:00
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"
reus
2020-07-23 00:52:44 +08:00
这类问题,全都在语言规范里写了的

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.
heimeil
2020-07-23 00:53:51 +08:00
定义 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 是指定字段名
byzf
2020-07-23 14:52:29 +08:00
建议过一遍入门教程.
chaleaoch
2020-07-25 11:10:12 +08:00
@byzf 谢谢 请问那本入门教程, 我看过 GO 语言圣经和 GO 高级编程 两本教材 书中的例子 没有类似的.
chaleaoch
2020-07-25 11:11:22 +08:00
@byzf 我说错了,这个例子就是 go 高级编程中的例子,但是 他没有说明为什么. Go 语言圣经里面没有类似例子.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/692343

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX