MST

星途 面试题库

面试题:Go中函数与接口结合实现简单图形计算

定义一个接口 `Shape`,包含 `Area` 方法用于计算图形面积。再定义 `Rectangle` 和 `Circle` 结构体,分别实现 `Shape` 接口的 `Area` 方法。最后编写一个函数 `CalculateArea`,该函数接受一个 `Shape` 接口类型的参数,并调用其 `Area` 方法返回面积。请写出完整代码。
41.3万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "math"
)

// 定义Shape接口
type Shape interface {
    Area() float64
}

// 定义Rectangle结构体
type Rectangle struct {
    Width  float64
    Height float64
}

// Rectangle实现Shape接口的Area方法
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// 定义Circle结构体
type Circle struct {
    Radius float64
}

// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

// 定义CalculateArea函数
func CalculateArea(s Shape) float64 {
    return s.Area()
}

你可以使用以下方式调用:

func main() {
    rectangle := Rectangle{Width: 5, Height: 3}
    circle := Circle{Radius: 4}

    fmt.Printf("Rectangle Area: %.2f\n", CalculateArea(rectangle))
    fmt.Printf("Circle Area: %.2f\n", CalculateArea(circle))
}

以上代码使用Go语言实现,定义了Shape接口以及RectangleCircle结构体来实现该接口的Area方法,并编写了CalculateArea函数来计算不同图形的面积。如果是其他编程语言,实现方式会有所不同,例如Java实现如下:

interface Shape {
    double Area();
}

class Rectangle implements Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double Area() {
        return width * height;
    }
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double Area() {
        return Math.PI * radius * radius;
    }
}

class AreaCalculator {
    public static double CalculateArea(Shape s) {
        return s.Area();
    }
}

调用方式如下:

public class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(5, 3);
        Circle circle = new Circle(4);

        System.out.printf("Rectangle Area: %.2f\n", AreaCalculator.CalculateArea(rectangle));
        System.out.printf("Circle Area: %.2f\n", AreaCalculator.CalculateArea(circle));
    }
}

上述Java代码定义了Shape接口,RectangleCircle类实现该接口,并提供了CalculateArea方法计算面积。这里以Go和Java为例展示了不同语言对该需求的实现方式。