MST

星途 面试题库

面试题:Go语言结构体方法的继承与重写模拟

Go语言没有传统面向对象语言中的继承概念,但可以通过组合等方式模拟类似功能。请编写代码,通过结构体组合模拟父结构体和子结构体,并实现子结构体对父结构体方法的“重写”。
44.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import "fmt"

// 定义父结构体
type Parent struct {
    Name string
}

// 父结构体的方法
func (p Parent) PrintInfo() {
    fmt.Printf("Parent: Name is %s\n", p.Name)
}

// 定义子结构体,通过组合包含父结构体
type Child struct {
    Parent
    Age int
}

// 子结构体“重写”父结构体的方法
func (c Child) PrintInfo() {
    fmt.Printf("Child: Name is %s, Age is %d\n", c.Name, c.Age)
}

你可以使用以下方式测试上述代码:

func main() {
    p := Parent{Name: "John"}
    p.PrintInfo()

    c := Child{Parent: Parent{Name: "Jane"}, Age: 10}
    c.PrintInfo()
    // 调用父结构体的原始方法
    c.Parent.PrintInfo() 
}

上述代码中,Parent 结构体是父结构体,有一个 PrintInfo 方法。Child 结构体通过组合的方式包含了 Parent 结构体,并且 Child 结构体定义了自己的 PrintInfo 方法,实现了对父结构体方法的“重写”。在 main 函数中,分别创建了 ParentChild 的实例,并调用它们的 PrintInfo 方法,同时也展示了如何调用父结构体被“重写”前的原始方法。