Go 中没有传统多态,但可以利用接口和反射实现类似效果:定义接口,明确方法集。创建多个类型,实现该接口。使用反射,动态调用方法,无需了解具体类型。

Go 中实现多态
如何实现?
Go 中没有传统意义上的多态,但可以使用接口和反射机制来实现类似于多态的行为。
接口:
立即学习“go语言免费学习笔记(深入)”;
反射:
实现步骤:
示例:
<code class="go">type Shape interface {
Area() float64
}
type Square struct {
side float64
}
func (s *Square) Area() float64 {
return s.side * s.side
}
type Circle struct {
radius float64
}
func (c *Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func main() {
shapes := []Shape{
&Square{side: 5},
&Circle{radius: 5},
}
for _, s := range shapes {
fmt.Println("Area:", reflect.ValueOf(s).MethodByName("Area").Call([]reflect.Value{})[0].Float())
}
}</code>优点:
缺点:
以上就是golang如何实现多态的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号