Golang程序 使用类查找矩形面积

Golang程序 使用类查找矩形面积

要使用类来计算矩形的面积,我们可以采取以下步骤

  • 定义一个具有长方形属性的 结构 ,如 宽度长度。
  • 定义一个方法来计算矩形的面积。
  • 方法中,实例化一个矩形的对象。
  • 调用 结构 方法,即 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程