用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
}
相关推荐
想不明白的过度思考者4 分钟前
Spring Boot 配置文件深度解析
java·spring boot·后端
想回家的一天5 小时前
ECONNREFUSED ::1:8000 前端代理问题
开发语言
cike_y5 小时前
Mybatis之解析配置优化
java·开发语言·tomcat·mybatis·安全开发
WanderInk6 小时前
刷新后点赞全变 0?别急着怪 Redis,这八成是 Long 被 JavaScript 偷偷“改号”了(一次线上复盘)
后端
Jay_Franklin6 小时前
SRIM通过python计算dap
开发语言·python
Slow菜鸟7 小时前
Java基础架构设计(三)| 通用响应与异常处理(分布式应用通用方案)
java·开发语言
吴佳浩7 小时前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
消失的旧时光-19437 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir7 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
tap.AI7 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能