在 golang 中,为什么我不能将结构用作嵌套结构类型?

In golang why I can't use the struct as nested struct type?

以下代码(play):

func main() {
    buf := bytes.NewBuffer(make([]byte, 0))
    rw := bufio.NewReadWriter(bufio.NewReader(buf), bufio.NewWriter(buf))
    var r *bufio.Writer
    r = rw
}

给出以下编译时错误:

cannot use rw (type *bufio.ReadWriter) as type *bufio.Writer in assignment

我期望的是将结构用作嵌套结构类型。但是如果我把r声明为io.Reader,这样就可以了,那我是不是应该转到interface?

不同类型无法赋值,GO不支持扩展

bufio.NewReadWriter() returns a concrete type, a pointer to a struct and bufio.Writer is also a concrete type, a struct. Neither *ReadWriter and *bufio.Writer is an interface!

Go 中没有自动类型转换,您不能将不同具体类型的值赋给变量。

您有 2 个选择:

  1. 由于 bufio.ReadWriter 嵌入了 *bufio.Writer,您可以简单地引用它并在作业中使用它:

    var r *bufio.Writer
    r = rw.Writer
    
  2. 或者你可以声明r为一个io.Writer(它是一个接口类型)这样你就可以给它赋值rw因为rw 实现 io.Writer:

    var r io.Writer
    r = rw
    

    尽管我认为在这种情况下创建 r 不是特别有用,因为无论何时您使用 r 也可以使用 rw.

查看 Go spec: Assignability:

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type is identical to T.
  • x's type V and T have identical underlying types and at least one of V or T is not a named type.
  • T is an interface type and x implements T.
  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
  • x is an untyped constant representable by a value of type T.

None 个案例适用于您的代码,因此它是无效的分配。

r被声明为io.Writer时,是下面的情况,因此它是有效的:

T is an interface type and x implements T.