gpt4 book ai didi

pointers - 指向接口(interface)的指针是不是接口(interface)错误?

转载 作者:IT王子 更新时间:2023-10-29 02:25:45 31 4
gpt4 key购买 nike

以下代码有效:

type Brace interface {}

type Round struct {
prev_ Brace
}

type Square struct {}

func main() {
var r Round
var s Square
r.prev_ = s
}

r.prev_ 现在是 s 的副本是真的吗?如何更改 Round 将包含指向 Brace 的指针?此代码不起作用:

type Brace interface {}

type Round struct {
prev_ *Brace
}

type Square struct {}

func main() {
var r Round
var s Square
r.prev_ = &s
}

因为错误:

cannot use &s (type *Square) as type *Brace in assignment: *Brace is pointer to interface, not interface

最佳答案

如错误所述:

cannot use &s (type *Square) as type *Brace in assignment: *Brace is pointer to interface, not interface

接口(interface)可以包装任何类型的值。但是您将结构包装在指针类型接口(interface)而不是接口(interface)中。这不是接口(interface)在 golang 中的工作方式。

如果你想传递一个结构体的地址。接口(interface)可以直接将指针包装到结构。无需创建指向接口(interface)的指针即可实现该目的。

type Brace interface {}

type Round struct {
prev_ Brace
}

type Square struct {}

func main() {
var r Round
var s Square
r.prev_ = &s
fmt.Printf("%#v", r)
}

Playground Example

在 Golang 中,您应该避免将指针传递给接口(interface):

The compiler will complain about this error but the situation can still be confusing, because sometimes a pointer is necessary to satisfy an interface. The insight is that although a pointer to a concrete type can satisfy an interface, with one exception a pointer to an interface can never satisfy an interface.

考虑变量声明,

var w io.Writer

打印函数 fmt.Fprintf 将满足 io.Writer 的值作为其第一个参数——实现规范 Write 方法的东西。这样我们就可以写

fmt.Fprintf(w, "hello, world\n")

但是,如果我们传递 w 的地址,程序将无法编译。

fmt.Fprintf(&w, "hello, world\n") // Compile-time error.

The one exception is that any value, even a pointer to an interface, can be assigned to a variable of empty interface type (interface{}). Even so, it's almost certainly a mistake if the value is a pointer to an interface; the result can be confusing.

Go playground 上查看.当您尝试将指针传递给接口(interface)时,您会发现您在代码片段中遇到的错误。

关于pointers - 指向接口(interface)的指针是不是接口(interface)错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51611086/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com