1024programmer Java Method inheritance and method overriding of anonymous fields in Go

Method inheritance and method overriding of anonymous fields in Go

// 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
 }

 //The method is overridden, but cannot be overloaded; if it is not overridden, the method of the anonymous field is inherited.
 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()
 }

The running results are as follows:

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

The above is the “Method Inheritance and Method Rewriting of Anonymous Fields in Go” introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will Reply to everyone promptly. We would also like to thank you all very much for your support!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/756367

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索