Go Language Object-oriented

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

The go language can declare new types through structs

Create a new type person

typestruct {    string    int}var'liming'p1.age = 18

Create a new type student, you can introduce the person all characters De Yin by anonymous field student

typestruct {    Person  //隐式引入    string    string}s1 := Student{Person{'zhangliang',23'hign school','new name'}s1.age   //23  可直接访问Person的字段s1.name  //new name 最外层优先访问,重载//zhangliang 通过匿名字段访问

Add a recipient struct to a function, or add a method to a struct

//此处传递是按值传递的,操作的是副本,若receiver为指针,则按引用传递,操作的是原实例对象boolean {    if18 {  //可以直接访问struct的字段        returntrue    }    returnfalse} s1.isAdult()  //trueintboolean {    s.age = newAge }s1.changeAge(23)

Method is the same as the inheritance of the field, all through the anonymous field

type HignSchoolStudet {    Student    string}//可函数重载funcint) boolean {    h.age = newAge + 12}h1 := HignSchoolStudet{Student{Person{'zhangliang',23'hign school'},'math'}

The interface interface, which provides a combination of common methods, provides a dynamic type

type people interface {changeage ()}
    var i  peoplei  = S1S1.  Changeage () i  = H1h1.  Age  

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.