How to approach the struct in Go method first experience

Source: Internet
Author: User

Code_017_struct_method_usage Project Main.gopackage mainimport ("FMT") type MyInt IntFunc (a MyInt) Add (b MyInt) MyInt {return a + B}func Add (A, b MyInt) MyInt {return a + b}type person struct {name string sex "byte Age Int}func" (p person) Printinfo () {fmt. Println (P.name, P.age)}func (P *person) Setinfopointer () {(*p). Name = "God_girl" p.sex = 1 p.age = 22}func (P person) Set Infovalue () {p.name = "god_like" p.sex = 1 P.age = 23}func Main () {/* has a function with a receiver, which we call method. In essence, a method is a function associated with a particular type. The func (receiver Receivertype) funcName (parameters) {results} 1) parameter receiver can be named arbitrarily. You can omit the parameter name if it has not been used in the method. The parameter receiver type can be T or *t. The base type T cannot be an interface or a pointer. Overloaded methods are not supported, that is, methods that have the same name but different parameters cannot be defined. 2) in the Go language, you can add an appropriate method to any custom type, including built-in types, but not pointer types. *///1) basic use var a MyInt = 1 var b MyInt = 1 fmt. Println ("a.add (b) =", A.add (b)) fmt. Println ("Add (a) =", add (A, b))//2) struct as receiver P: = person{"Ck_god", 0, +} p.printinfo ()//3) struct value semantics and referential semantics p1: = person{"wan Glaoji ", 0, +} fmt. Println ("pre-function call =", p1) (&P1). Setinfopointer () FMT.println ("function call after =", p1) fmt. Println ("==========================") P2: = person{"Ck_god", 0, + FMT. Println ("pre-function call =", p2) P2. Setinfovalue () fmt. PRINTLN ("after function call =", p2)//function Call after = {Mike 109 18}}

Methods of the struct in Go method first experience

Related Article

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.