MST
星途 面试题库

面试题:Go接口响应式编程之基础接口实现

在Go语言的接口响应式编程中,定义一个简单的`Shape`接口,包含`Area`方法用于计算面积。然后实现`Circle`和`Rectangle`结构体,使其满足`Shape`接口。并编写一个函数,接受`Shape`接口类型参数,调用`Area`方法并打印结果。
39.5万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "math"
)

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

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

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

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

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

// 接受Shape接口类型参数并调用Area方法打印结果的函数
func printArea(s Shape) {
    fmt.Printf("Area is: %f\n", s.Area())
}

你可以使用以下方式调用这些函数和结构体:

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

    printArea(circle)
    printArea(rectangle)
}