用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
}
相关推荐
多多*1 小时前
LUA+Reids实现库存秒杀预扣减 记录流水 以及自己的思考
linux·开发语言·redis·python·bootstrap·lua
Wish3D2 小时前
阿里云OSS 上传文件 Python版本
开发语言·python·阿里云
凤年徐2 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii2 小时前
C++11 右值引用:从入门到精通
开发语言·c++
朝新_5 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir5 小时前
Calendar类日期设置进位问题
java·开发语言
XMYX-05 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
风逸hhh6 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮6 小时前
Python训练第四十三天
开发语言·python
@yanyu6667 小时前
springboot实现查询学生
java·spring boot·后端