用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
}
相关推荐
dingdingfish4 分钟前
Bash学习 - 第3章:Basic Shell Features,第5节:Shell Expansions
开发语言·学习·bash
rainbow68895 分钟前
C++开源库dxflib解析DXF文件实战
开发语言·c++·开源
deepxuan6 分钟前
Day7--python
开发语言·python
禹凕21 分钟前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
苏三说技术23 分钟前
xxl-job 和 elastic-job,哪个更好?
后端
三小河31 分钟前
Agent Skill与Rules的区别——以Cursor为例
前端·javascript·后端
蜡笔小马34 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
IOsetting34 分钟前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
三小河44 分钟前
前端视角详解 Agent Skill
前端·javascript·后端
林开落L1 小时前
从零开始学习Protobuf(C++实战版)
开发语言·c++·学习·protobuffer·结构化数据序列化机制