ZBLOG

golang struct能内嵌interface吗

是的,Go语言中可以在结构体(struct)中内嵌接口(interface)。通过这种方式,结构体可以直接获得内嵌接口定义的方法集合,并且可以实现该接口所定义的方法。这样做可以简化代码,提高代码复用性。以下是一个示例:

package main

import "fmt"

type Shape interface {
    Area() float64
}

type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

type Square struct {
    SideLength float64
}

func (s Square) Area() float64 {
    return s.SideLength * s.SideLength
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

type Geometry struct {
    Shape // 内嵌Shape接口类型,相当于匿名字段
}

func main() {
    rect := Rectangle{Width: 5, Height: 10}
    sq := Square{SideLength: 7}
    
    geom1 := Geometry{Shape: rect} // 使用Rectangle作为Shape接口实现对象初始化Geometry
    
    fmt.Println("Area of rectangle:", geom1.Area()) // 调用内嵌的Shape接口方法

	geom2 := Geometry{Shape: sq} // 使用Square作为Shape接口实现对象初始化Geometry
	
	fmt.Println("Area of square:", geom2.Area()) // 调用内嵌的Shape接口方法
	
	circle := Circle{Radius: 3}
	
	geom3 := Geometry{Shape: circle} // 使用Circle作为Shape接口实现对象初始化Geometry
	
	fmt.Println("Area of circle:", geom3.Area()) // 调用内嵌的Shape接口方法
}

上述示例中,通过在Geometry结构体中内嵌了Shape接口类型,使得Geometry可以直接调用内嵌的Shape接口定义的方法。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8395

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?