阅读背景:

【Golang入门】Golang第一天心得

来源:互联网 

生活所迫,入门一下Go

很奇葩的第一点,接口 package main import ( "fmt" ) // 定义一个接口 type Shape interface { Area() float64 } // 定义一个矩形类型 type Rectangle struct { Width float64 Height float64 } // 矩形类型实现Shape接口的Area方法 func (r Rectangle) Area() float64 { return r.Width * r.Height } // 定义一个圆形类型 type Circle struct { Radius float64 } // 圆形类型实现Shape接口的Area方法 func (c Circle) Area() float64 { return 3.14159265359 * c.Radius * c.Radius } func main() { // 创建一个矩形对象 rectangle := Rectangle{ Width: 4, Height: 5} // 创建一个圆形对象 circle := Circle{ Radius: 3} // 使用接口来计算不同形状的面积 shapes := []Shape{ rectangle, circle} for _, shape := range shapes { fmt.Printf("Area of the shape is: %.2f\n", shape.Area()) } } 很奇葩的第一点,接口 package main import ( "fmt"



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: