Golang polymorphism and C + + a little difference

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The following code is validated by the go1.5

Package Main
Import (
"FMT"
)
Type person struct {
Name string
Age  int
Tel  string
}
Type Student struct {
person//has another field
School string
}
Func (P *person) Print () {
Fmt. Printf ("print\n")
P.hello ()//Hello to Person
}
Defines a method for passing values on person
Func (P *person) Hello () {
P.tel = "186"
Fmt. Printf ("Person My name was%s, and my tel number is%s\n", P.name, P.tel)
}
Polymorphic
Func (P *student) Hello () {
P.tel = "0117"
Fmt. Printf ("Student My name is%s, and my tel number is%s\n", P.name, P.tel)
}
Func Main () {
Anna: = new (Student)
Anna. Person.name = "Jim"
Anna.tel = "12345678"
Anna. Hello ()  //student My name is Jim, and my tel number is 0117
Anna. Person.hello ()  //person My name is Jim, and my tel number is 186
Anna. Print ()  //print
Here in C + + it calls student's Hello interface
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.