官术网_书友最值得收藏!

  • Security with Go
  • John Daniel Leon
  • 106字
  • 2021-06-30 19:06:50

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)
}
主站蜘蛛池模板: 桐庐县| 宁津县| 信宜市| 西充县| 衡山县| 盐城市| 南郑县| 五河县| 朝阳区| 宁都县| 马龙县| 五华县| 太湖县| 绥德县| 盘山县| 西安市| 呼玛县| 井研县| 佛教| 隆安县| 白朗县| 邢台市| 富源县| 民丰县| 四子王旗| 唐河县| 蒙自县| 浑源县| 永嘉县| 滨海县| 安福县| 文安县| 保德县| 达拉特旗| 星子县| 泸水县| 金沙县| 高要市| 广平县| 应城市| 洪泽县|