用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
}
相关推荐
MC丶科2 小时前
【SpringBoot常见报错与解决方案】中文乱码?Spring Boot 统一解决前后端中文乱码问题(含 Postman 测试)!别再百度“加 UTF-8”了!
spring boot·后端·postman
leaves falling4 小时前
C语言内存函数-
c语言·开发语言
至为芯5 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
小羊羊Python6 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++
浩瀚地学6 小时前
【Java】JDK8的一些新特性
java·开发语言·经验分享·笔记·学习
l1t6 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
XXOOXRT7 小时前
基于SpringBoot的加法计算器
java·spring boot·后端·html5
yugi9878387 小时前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab
moxiaoran57538 小时前
Go语言的错误处理
开发语言·后端·golang
yugi9878388 小时前
MATLAB的多层感知器(MLP)与极限学习机(ELM)实现
开发语言·matlab