Go中匿名字段的方法继承与方法重写

栏目: Go · 发布时间: 7年前

内容简介:运行结果如下:
// code_019_struct_anonymous_field_method project main.go
package main

import (
    "fmt"
)

type Person struct {
    name string
    sex  byte
    age  int
}

func (p *Person) PrintInfo() {
    fmt.Printf("Person:%s,%c,%d\n", p.name, p.sex, p.age)
}

type Student struct {
    Person
    id   int
    addr string
}

//方法被重写,但是不能被重载;若未被重写,则继承匿名字段的方法
func (s *Student) PrintInfo() {
    fmt.Printf("Student:%s,%c,%d\n", s.name, s.sex, s.age)
}

func main() {
    p := Person{"ck_god", 'm', 18}
    p.PrintInfo()

    s := Student{Person{"god_girl", 'f', 20}, 2, "sz"}
    s.PrintInfo()
    s.Person.PrintInfo()
}

运行结果如下:

Person:ck_god,m,18
Student:god_girl,f,20
Person:god_girl,f,20

以上所述就是小编给大家介绍的《Go中匿名字段的方法继承与方法重写》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

High Performance JavaScript

High Performance JavaScript

Nicholas C. Zakas / O'Reilly Media / 2010-4-2 / USD 34.99

If you're like most developers, you rely heavily on JavaScript to build interactive and quick-responding web applications. The problem is that all of those lines of JavaScript code can slow down your ......一起来看看 《High Performance JavaScript》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具