Security with Go
上QQ阅读APP看书,第一时间看更新

Inheritance

There is no inheritance in Go, but you can embed types. Here is an example of a Person and Doctor types, which embeds the Person type. Instead of inheriting the behavior of Person directly, it stores the Person object as a variable, which brings with it all of its expected Person methods and attributes:

package main

import (
"fmt"
"reflect"
)

type Person struct {
Name string
Age int
}
type Doctor struct {
Person Person
Specialization string
}

func main() {
nanodano := Person{
Name: "NanoDano",
Age: 99,
}
drDano := Doctor{
Person: nanodano,
Specialization: "Hacking",
}

fmt.Println(reflect.TypeOf(nanodano))
fmt.Println(nanodano)
   fmt.Println(reflect.TypeOf(drDano))
fmt.Println(drDano)
}