Golang 程序使用类查找矩形的面积
go programmingserver side programmingprogramming更新于 2025/4/22 4:52:17
要使用类查找矩形的面积,我们可以采取以下步骤
- 定义一个具有矩形属性(例如宽度和长度)的struct。
- 定义一个方法来计算矩形的面积。
- 在main方法中,实例化一个矩形对象。
- 调用struct方法,即Area,来计算矩形的面积。
- 打印矩形的面积。
示例
package main import ( "fmt" ) type Rectangle struct { breadth int len int } func (r *Rectangle)Area() int{ return r. len * r.breadth } func main(){ rectangle := Rectangle{ breadth: 10, len: 8, } fmt.Println("Area of the rectangle:", rectangle, " is: ", rectangle.Area()) }
输出
Area of the rectangle: {10 8} is: 80