method, Interface Learning notes

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

Before in the development of the line, not to think about some of the details of the problem, such as interface in the end what is the use, now well summarized under
1. Methods

package mainimport "fmt"import "reflect"type S struct {    a int}func (s S) Set1(v int) {    s.a = v}func (s *S) Set2(v int) {    s.a = v}func (s *S) Get() int {    return s.a}func main() {    var s1 S    var s2 *S    s1.Set1(100)//receiver类型为T的实例,Set1修改的只是s1的副本    fmt.Println(s1.Get())    s1.Set2(100)//receiver类型为*T的实例,Set2修改的是s1的引用    fmt.Println(s1.Get())    fmt.Println("....s1 Method Set....")//receiver类型为T只包含T的方法集,receiver类型为*T包含T和*T的方法集    DumpMethodSet(s1)    fmt.Println("....s2 Method Set....")    DumpMethodSet(s2)}func DumpMethodSet(i interface{}) {    MethodSet := reflect.TypeOf(i)    for i := 0; i < MethodSet.NumMethod(); i++ {        fmt.Println(MethodSet.Method(i).Name)    }}

Note that invoking a method with an instance of receiver type T can actually call all methods of T and *t, not constrained by the method set, and the editor will automatically find the corresponding method and convert the receiver argument

The following example shows what error can be caused by the difference between T and *t as the receiver method set

package maintype I interface {    Set1(int)    Set2(int)}type S struct {    a int}func (s S) Set1(v int) {    s.a = v}func (s *S) Set2(v int) {    s.a = v}func main() {    var s1 S    var s2 *S    var a1 I = s1//ERROR: cannot use s1 (type S) as type I in assignment:                 //S does not implement I (Get method has pointer receiver)    var a2 I = s2    _ = a1    _ = a2}

2. Interface

Package Mainimport "FMT" type Pcer interface {//1. Interface naming habits with ER end getbrand () string Memoryer//2. Interface can be embedded interface Cpuer// 3. Interface is just a set of methods, without data fields Printinfo ()}//memory strip type Memoryer interface {getmemory () Int}//cputype Cpuer interface {GETCPU () Int}type highendpc struct {Brand string memorycap int cpukernlcnt int Gpumemorycap int}type Lowhen DPC struct {Brand string memorycap int cpukernlcnt int}func (self *highendpc) Getbrand () string {RET Urn self. Brand}func (self *highendpc) getmemory () int {return self. Memorycap}func (self *highendpc) getcpu () int {return self. Cpukernlcnt}func (self *highendpc) getgpu () int {return self. Gpumemorycap}func (self *highendpc) printinfo () {fmt. Printf ("High-end PC brand:%s, memory size%d, processor core%d, memory size%d \ n", self.) Brand, self. Memorycap, self. Cpukernlcnt, self. GPUMEMORYCAP)}func (self *lowhendpc) Getbrand () string {return to self. Brand}func (self *lowhendpc) getmemory () int {return self. Memorycap}func (Self *loWHENDPC) getcpu () int {return self. Cpukernlcnt}func (self *lowhendpc) printinfo () {fmt. Printf ("Low-end PC Brand:%s, memory size%d, processor cores%d \ n", self.) Brand, self. Memorycap, self. CPUKERNLCNT)}func Main () {companypc: = lowhendpc{"Dell", 8, 2} HOMEPC: = highendpc{"DIY", 4, one} MyPC: = []p Cer{&companypc, &AMP;HOMEPC}//4.pcer is the abstraction of Companypc and Homepc, as long as the method implemented in the interface, you can plug in for _, PC: = Range MyPC {pc. Printinfo ()}}

Operation Result:
Low-end PC Brand: Dell, Memory size 8, processor core Number 2
High-end computer brand: DIY, Memory size 16, processor core number 4, memory size 11

This example shows some of the features and applications of interface, similar to the polymorphic idea of C + +, but does not need to explicitly allow structs to "inherit" the interface set of methods, as long as the struct implements all the methods in interface, This implementation refers to a method that implements the same name, a parameter list (excluding parameter names), and a return value.

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.