用Golang实现图形面积计算

计算正方形面积

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

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
}

你可能感兴趣的:(golang,开发语言,后端)