gpt4 book ai didi

pointers - 使用接口(interface)时操作结构字段

转载 作者:IT王子 更新时间:2023-10-29 01:54:23 27 4
gpt4 key购买 nike

标题可能具有误导性,但重点是......

我有一个接口(interface)表达式:

type Expression interface {
String() // skiped in implementation below
}

接口(interface)由多个结构体实现,其中一些结构体实现与字段值相同的接口(interface):

type IdentExpression struct {
value string
}

type UnaryExpression struct {
token string
value Expression
}

func (a *UnaryExpression) Simplify() {
var finalValue Expression
switch a.value.(type) {
case UnaryExpression:
tmp := a.value.(UnaryExpression)
switch tmp.value.(type) {
case UnaryExpression:
tmp = tmp.value.(UnaryExpression)
finalValue = tmp.value
}
}

a.value = finalValue
}

给定表达式-(-(-(1)))UnaryExpression.Simplify() 会将表达式简化为-(1)。 ( play )

我想用 Simplify() 方法扩展接口(interface):

type Expression interface {
Simplify()
String() string
}

// ...

func (a IdentExpression) Simplify() {} // do nothing

结果代码不起作用(play):

main.go:29: impossible type switch case: a.value (type Expression) cannot have dynamic type UnaryExpression (missing Simplify method)

main.go:30: impossible type assertion:

UnaryExpression does not implement Expression (Simplify method has pointer receiver)

main.go:59: cannot use UnaryExpression literal (type UnaryExpression) as type Expression in field value:

UnaryExpression does not implement Expression (Simplify method has pointer receiver)

main.go:60: cannot use UnaryExpression literal (type UnaryExpression) as type Expression in field value:

UnaryExpression does not implement Expression (Simplify method has pointer receiver)

我找到了 this answer ,看起来很相似,但我不知道如何在我的案例中应用它。

最佳答案

这里的关键是您在关于 UnaryExpressionSimplify() 定义中使用指针接收器:

func (a *UnaryExpression) Simplify()

您正在实现的其他方法不使用指针接收器:

// One example
func (a IdentExpression) Simplify() {}

通常,在 Go 中,让同一类型的所有方法使用相同类型的接收器被认为是最佳实践(即,如果一个方法使用指针接收器,它们都应该。同样地,如果一个方法使用非指针接收器,它们都应该针对特定类型)。

在这种情况下,如果您从 UnaryExpressionSimplify 方法中删除指针接收器,代码将编译。希望这对您有所帮助!

编辑:Here is a more comprehensive answer that explains exactly why this error happens, it's really a good read.

关于pointers - 使用接口(interface)时操作结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257237/

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