You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Go语言中可返回结构体指针给接口类型返回值?

Go接口返回结构体指针的原因解析

先看你的代码:

type Person interface {
    getName() string
}

type person1 struct {
    name string
}

func (p person1) getName() string {
    return p.name
}

func testing(name string) Person {
    return &person1{
        name: name,
    }
}

func main() {
    // Call the getName method to print the name
    fmt.Println(testing("Rambo").getName())
}

你的疑问:testing函数的返回类型为Person接口,但却可以返回person1结构体的指针&person1,这是为什么?


核心原因在于Go的接口实现规则:

  • Go的接口是隐式实现的,不需要显式声明“我实现了某个接口”,只要类型(包括指针类型)实现了接口定义的所有方法,就自动属于该接口类型。
  • 你的代码中,person1用值接收者实现了getName()方法,这意味着:
    1. person1值类型本身满足Person接口的要求;
    2. *person1指针类型也自动拥有这个方法——Go会自动处理指针的解引用逻辑,让指针类型可以调用值接收者的方法,所以*person1同样实现了Person接口。

因此,testing函数返回&person1(即*person1类型)完全符合返回Person接口的要求,编译器会自动把这个指针包装成接口类型返回。


内容的提问来源于stack exchange,提问作者Scáthach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:33:19