用Golang实现图形面积计算

计算正方形面积

go 复制代码
package main

import "fmt"

type square struct {
	side float32
}

func (s square) area() float32 {
	return s.side * s.side
}

func main() {
	s := square{side: 10}
	fmt.Printf("%T\n", s)
	fmt.Println(s.area())
}

计算正方形、圆形、矩形面积,写一个通用的函数info和一个通用的interface

go 复制代码
package main

import "fmt"
import "math"

type square struct {
	side float32
}

func (s square) area() float32 {
	return s.side * s.side
}

type circle struct {
	radius float32
}

func (c circle) area() float32 {
	return math.Pi * c.radius * c.radius
}

type rectangle struct {
	width  float32
	length float32
}

func (r rectangle) area() float32 {
	return r.width * r.length
}

type shape interface {
	area() float32
}

func info(sp shape) {
	fmt.Println("shape area : ", sp.area())
}

func main() {
	s := square{side: 10}
	c := circle{radius: 10}
	r := rectangle{width: 10, length: 10}

	info(s) // 打印 shape area :  100
	info(c) // 打印 shape area :  314.15927
	info(r) // 打印 shape area :  100
}
相关推荐
乌鸦94412 分钟前
《类和对象(下)》
开发语言·c++·类和对象+
炒空心菜菜22 分钟前
SparkSQL 连接 MySQL 并添加新数据:实战指南
大数据·开发语言·数据库·后端·mysql·spark
多多*1 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
前进的程序员1 小时前
嵌入式开发中 C++ 跨平台开发经验与解决方案
开发语言·c++
乌夷1 小时前
axios结合AbortController取消文件上传
开发语言·前端·javascript
神仙别闹1 小时前
基于C#+MySQL实现(WinForm)企业设备使用信息管理系统
开发语言·mysql·c#
czhaii2 小时前
PLC脉冲位置 单片机跟踪读取记录显示
开发语言·c#
alden_ygq2 小时前
当java进程内存使用超过jvm设置大小会发生什么?
java·开发语言·jvm
蜗牛沐雨2 小时前
Rust 中的 `PartialEq` 和 `Eq`:深入解析与应用
开发语言·后端·rust
Python私教2 小时前
Rust快速入门:从零到实战指南
开发语言·后端·rust