从如下代码开始:

type Foo struct {
    V bool
}

func (f Foo) bar() bool {
    return f.V
}

是否允许在不增加主版本号的情况下更改为func (f *Foo) bar() bool?也就是说,假设您知道您的类型没有线程安全问题.如果是这样,反向更改也是允许的,对吗?

据我所知,任何调用函数的代码,无论变量是值还是指针,在这两个更改之后都将继续编译并按预期工作.

推荐答案

根据 comments ,this answer答案提供了一个很好的总结,T*T接收者类型.以下是从func (f Foo) bar() bool更改为func (f *Foo) bar() bool会 destruct 现有代码的几个示例.

示例1:T不可寻址(playground):

type Foo struct {
    V bool
}

func (f *Foo) bar() bool { // Change to `(f Foo)` and this will work
    return f.V
}

func x() Foo {
    return Foo{true}
}

func main() {
    fmt.Printf("%v", x().bar())
}

示例2:接口(playground):

type Foo struct {
    V bool
}

func (f *Foo) bar() bool { // Change to `(f Foo)` and this will work
    return f.V
}

type Fooer interface {
    bar() bool
}

func main() {
    var x Fooer
    x = Foo{}
    fmt.Println(x.bar())
}

Go相关问答推荐

Golang Cososdb-gremlin连接

如何执行asn 1 marshal/unmarshal和omit字段?

包裹网.Conn导致挂起读取

如何在gofiber/websocket/v2中设置状态代码和原因

通过 Terraform 中的 MapNestedAtribute 进行迭代

如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf struct ?

Github Actions Go lambda 项目不同的 sha256sums

错误!在为 age-viewer-go 运行 wails dev 或 wails build 命令时

gopacket:IP-in-IP 数据包上的解码层

golang:解组动态 YAML 注释

如何判断范围内的字段?

类型/ struct 函数的 GoDoc 示例函数

如何模仿联合类型

获取切片元素的地址是否意味着 Go 中元素的副本?

Dockerfile 问题 - 为什么找不到二进制 dlv - 没有这样的文件或目录

Go 泛型:自引用接口约束

在 Go 中发送 ack 和 term 后消息仍在 nats 限制队列中

为什么时间很短.睡眠时间比基准测试中要求的(约 300 ns)长?

使用 Golang SQL 驱动程序连接到snowflake

Go Flag 用法 描述 包含 Word 值