The basic summary of Go language surface combination to object programming

Source: Internet
Author: User

The go language object-oriented programming is simple and clean, through the non-intrusive interface model, the need to negate the complexity of traditional object-oriented programming languages, such as C/C + + Java, we find that even a simple combination in go can achieve the traditional object-oriented language effect, and the coupling is very low, According to one of the authors of Go, one of the authors of the C language: Go is a better C language.1, go any type any is interface{} type, namely the empty interface, can assign the value to any type2. You can add the appropriate method for other types of built-in types that do not include pointer types but note that you must use aliases. For packagingRemember that you want to add a new method to the type, then define the type alias, the alias and the original type is not the same as the new typeyou can only add methods to non-local types in Go ... That is, int cannot add method requires type int int to add method to intPackage Mainimport ("FMT") type Integer intfunc (A-integer) less (b integer) bool {return A<b}func main () {var a I Nteger=1 r:=a.less (2) fmt.    Println (r)}/////usage 2 combination of pointers package mainimport ("FMT") type Integer IntFunc (a *integer) less (b Integer) bool {*a-=10 Return *a<b}
Type Int IntFunc (a *int) lessine (b int) bool{return *a<b}func main () {var a integer=1 var aa int=10 A=integer (AA) R:=a.less (2) fmt. Println (R)}
3. The this pointer does not exist in go, and the object is passed through the syntax sugar explicitlyThere is no hidden this pointer in the GO language: The object that the  method imposes (that is, "objects") is explicitly passed, not hidden, and the target (i.e. "object") applied by the  method does not need to be a pointer, nor does it have to be called this.4, after the type of alias is the new type is the only cast to usePackage Mainimport ("FMT") type Integer intfunc (A-integer) less (b integer) bool {return A<b}func main () {var a I nteger=1 var aa int=10 A=integer (AA)//Do not cast will compile an errorR:=a.less (2) fmt. Println (R)}5. Value semantics and references in GoChannel Map is essentially a pointer because copying them doesn't make sense .... Array slicing []type is essentially a value type interface interface is very importantThe difference between value semantics and referential semantics is assignment, such as the following example: B = ab. Modify () If the modification of B does not affect the value of a, then this type belongs to the value type. If the value of a is affected, then this type is a reference type. Most types in the go language are based on value semantics, including:  Basic types, such as Byte, int, bool, float32, float64, and string,  composite types, array, struct (struct), and pointers (pointer). The value semantics of the type in the go language are very thorough. The reason we say this is because of the array. If the reader has learned the C language before, it will know that the arrays in C are quite special. Passing an array by function is based on referential semantics, but when you define an array variable in a struct, it is based on the value semantics (the array is completely copied when it is assigned to a struct). There is no difference between the array and the base type in the go language, which is a purely value type, for example: var a = [3]int{1, 2, 3}var B = ab[1]++fmt. Println (A, B) the operation results of the program are as follows: [1 2 3] [1 3 3]. This indicates that the B=a assignment statement is a complete copy of the array contents. To express a reference, you need to use the pointer: var a = [3]int{1, 2, 3}var B = &ab[1]++fmt. Println (A, *b) the program runs as follows: [1 3 3] [1 3 3] This indicates that the B=&a assignment statement is a reference to the contents of the array. The type of variable B is not [3]int, but *[3]int type. There are 4 types in the go language that are more specific and look like reference types, as shown below
Array Slice: An interval that points to an array. map: A very common data structure that provides key-value query capabilities. channel: Communication facilities between the Executive Body (goroutine).  Interface (interface): An abstraction of a set of types that satisfy a contract. However, this does not affect the use of the Go language type as value semantics. Let's take a look at these 4 types. An array slice is essentially an interval, and you can roughly refer to []t as: type slice struct {first *t len int cap int} because the inside of an array slice is a pointer to an array, it's not surprising that you can change the array element you're pointing to. The assignment of the array slice type itself is still value semantics. Map is essentially a dictionary pointer, and you can roughly represent map[k]v as: type map_k_v struct {//...} type map[k]v struct {Impl *map_k_v} based on pointers, we can fully customize a reference type, such as : type integerref struct {impl *int}channel and map are similar, essentially a pointer. The reason they are designed as reference types instead of uniform value types is that full replication of a channel or map is not a regular requirement. Similarly, the interface has referential semantics because it maintains two pointers internally, indicating that the status of the type interface struct {data *void itab *itab} interface is very important in the go language. On the internal implementation of the interface details, in the later high-level topic, we carefully analyzed.7. Structure combination non-inheritance in Go languageThe Go language structure (struct) has the same status as other language classes (class), but the go language discards a large number of object-oriented features, including inheritance, and retains only the most basic features of the combination (composition). The combination is not even an object-oriented feature, because in a procedural programming language such as C, there are also structs and combinations. A combination is just the basis for forming a composite type. As we said above, all the Go language types (except pointer types) can have their own methods. In this context, the structure of the go language is only a very common composite type, bland. For example, we define a rectangle type: type Rect struct {x, y float64 width, height float64} and then we define the Member method area () to calculate the size of the rectangle: func (R *rect) areas () float64 {return r.width * R.height} shows that the use of structs in the go language is not significantly different from the C language.8, go in the combination of essence to create the structure of pointers and for the structure of the expansion of member functions when ..... The difference between passing a value type and a pointer typePackage Mainimport "FMT" type Rect struct{x, y float64 width,height float64}/// if written as RCT Rect, then internal modifications do not affect the external structure/// if written as rct*rect, internal modifications affect the value of the external structure, which is the effect of the pointer.Func (RCT *rect) area () float64{rct.width=1000///may also (*RCT). width=1000.return Rct.width*rct.height}func Main () {rct:=new (Rect)//For struct pointer,... Call a method as direct as a value type. The only difference is that the address value can be modified as a parameter pass//So there are two options when making a combination//Can be written as Var rct*rect=&rect{}//can also be written as Var RCT rect=rect{}//var RCT *rect=new (Rect)// can also be written as Var RCT rect=rect{1,2,3,4} rct.width=10.0 rct.height=10.0 area:=rct. Area () Fmt. Println (area) fmt. Println (Rct.width)}

9, the common combination of inheritance ......... ......... Combined pointer inheritance and override and function member name collisions//Inherit by value typePackage Mainimport "FMT"//go in the anonymous combination .... You can inherit from an object or anonymously from a pointer ...//anonymous inheritance removes the package name,,, so you cannot inherit the same class name at the same time   even if it is not in the same package type Base struct{     Name string     Age  uint8}///combines two function func (pbase*base) showname () {    &NBSP;FMT for the Base structure. Println ("Age", Pbase.name)}func (pbase*base) showage () {    &NBSP;FMT. Println ("Age", Pbase.age)}//Create sub struct type sub struct{   //Combined base Modify memory model    //anonymous combination into base is unknown to the caller    //Even though we cover the base method, we can still pass XXX. Base.xxx () Call the method of the base class    //If it is *base we need to manually add new base at the call or run an error     Base  }func (psub*sub) ShowName () {  FMT. Println ("Before Sub ShowName")     PSub.Base.showName ()     FMT. Println ("After Sub showname")}func Main () {      obj:=new (Sub)       obj. Name= "Zhang San"       obj. age=15      Obj.showname ()       Obj.showage ()}///inherits by pointer type Package Mainimport "FMT"//go in the anonymous combination .... You can inherit from an object or anonymously from a pointer ...//anonymous inheritance removes the package name,,, so you cannot inherit the same class name at the same time   even if it is not in the same package type Base struct{     Name string     Age  uint8}///combines two function func (pbase*base) showname () {    &NBSP;FMT for the Base structure. Println ("Age", Pbase.name)}func (pbase*base) showage () {    &NBSP;FMT. Println ("Age", Pbase.age)}//Create sub struct type sub struct{   //Combined base Modify memory model    //anonymous combination into base is unknown to the caller    //Even though we cover the base method, we can still pass XXX. Base.xxx () calls the method of the base class     *base  }func (psub*sub) showname () {  FMT. Println ("Before Sub ShowName")     PSub.Base.showName ()     FMT. Println ("After Sub showname")}func Main () {      obj:=new (Sub)    //due to the use of pointer inheritance we want to set the memory object of the anonymous composition template Address       obj. base=&base{}      obj. Name= "Zhang San"       obj. age=15      Obj.showname ()       Obj.showage ()}
10, the Go language visibility permission is the package level, outside the package can not access the lowercase beginning members of the package ... It doesn't matter in the bag

11, go non-intrusive interface and implementationthe/////go language automatically generates a corresponding function for each member function, such as func (a *a), which automatically generates Func (a a) ...///Not in reverse because Func (a a) is passing a formal parameter (&a). XX () changes the parameter copy instead of the external classPackage Mainimport "FMT"///non-intrusive interface////interface and implement full analysis to reduce coupling//The implementation side is only responsible for implementing the interface side only to encapsulate their excuses on line ... Implementations do not even know that there is a presence of this interface that is the feature of Go's non-intrusive interface type IFly interface{fly ()}type Isay interface{Say ()}type Bird struct{}//due to Anonymous delivery comes in that the assignment of the pointer type to the interface must be pointer func (Pbird*bird) Fly () {FMT. Println ("I am a bird, I Can Fly ()!")} Because an anonymous pass is not a pointer type is a value type, the interface assignment can be not a pointer but a value of func (Pbird Bird) say () {FMT. Println ("I am a bird, I can say ()!")} Func Main () {birdobj:=bird{} var iFly ifly=&birdobj ifly.fly () var isay isay=birdobj Isay.say ()}13, the interface can be assigned to each otherinterfaces that implement the same method can be assigned to each other, and if interface B is a non-superset, a can be assigned a value of BAn object cannot be assigned to an interface, and a breeding interface can be assigned to an object that implements some method or an interface object that contains his method.Package Mainimport "FMT"///non-intrusive interface////interface and implement full analysis to reduce coupling//The implementation side is only responsible for implementing the interface side only to encapsulate their excuses on line ... The realization side does not even know that there is a presence of this interface that is the feature of Go non-intrusive interface type IFly interface{fly ()}type Isay interface{Say ()}type IFly1 interface{FL Y ()}type ISay1 interface{Say ()}type Bird struct{}//The assignment of the pointer type to the interface must be pointer func (Pbird*bird) Fly () {FMT, because it is passed in anonymously. Println ("I am a bird, I Can Fly ()!")} Because an anonymous pass is not a pointer type is a value type, the interface assignment can be not a pointer but a value of func (Pbird Bird) say () {FMT. Println ("I am a bird, I can say ()!")} Func Main () {birdobj:=bird{} var iFly ifly=&birdobj ifly.fly () var isay isay=birdobj Isay.say () assignment between////interfaces var iFly1 ifly1=ifly ifly1.fly ()}
14. The value types in Go are very thorough arrays are value types
15. Adding a string () method to a type is equivalent to using ToString in other languages for print outputPackage Mainimport "FMT"///non-intrusive interface////interface and implement full analysis to reduce coupling//The implementation side is only responsible for implementing the   interface side only to encapsulate their excuses on line ... The realization side does not even know that there is a presence of this interface that is the feature of Go non-intrusive interface type IFly interface{    Fly ()}type Isay interface{    Say ()}type IF Ly1 interface{    Fly ()}type ISay1 interface{    Say ()}type Bird struct{     }//due to anonymous delivery The incoming pointer type is assigned to the interface must be pointer func (Pbird*bird) Fly () {   fmt. Println ("I am a bird, I Can Fly ()!")} Because an anonymous pass is not a pointer type is a value type, the interface assignment can be not a pointer but a value of func (Pbird Bird) say () {   fmt. Println ("I am a bird, I can say ()!")} Func (Pbird Bird) String () string{   return "Aaaaaaaaaa"}func Main () {     birdobj:=bird{}           var iFly ifly=&birdobj     ifly.fly ()      var I Say isay=birdobj     isay.say ()      ////interface Assignment      var iFly1 ifly1=ifly& nbsp    ifly1.fly ()     &NBSP;FMT. Println (Birdobj)}
16, the combination of interfaces is to combine multiple interfaces together ... Only functions in the interface have no propertiesType IFly interface{fly ()}type Isay interface{Say ()}type IFly1 interface{Fly ()}type ISay1 interface{Say ()} Type Isay_fly interface{Isay IFly}
17, interface query Obj,ok=val. (Interface) Returns the interface of the query and returns the query resultsx. (type) Get type can only be used in switchx. (otertypeinterface) Determines whether x is the specified interface type that returns the specified interface object, and the query resultsIn the go language, it is also more straightforward to ask the type of object instances that the interface points to, for example: var v1 interface{} = ... switch V: = v1. (type) {    Case INT:    //Now the type of V is int    case string://Now the type of V is string  ...} Just as there are many species in real life, the types in the language are countless, so type queries are not often used. It is more of a supplement that needs to be used in conjunction with interface queries, such as: Type Stringer interface {    String () String} func Println (args ... interface{}) {& nbsp   for _, arg: = Range args {         Switch V: = v1. ( Type) {            Case INT:                        //Now the type of V is int            Case string:                    //Now the type of V is string            default:            If V, OK: = arg. (Stringer); OK {//Now the type of V is stringer                val: = v.string ()       &NBSP ;       &NBsp ...           } else {               //... &nbs P          }       }   }} Of course, the println () of the Go Language standard library is much more complex than this example Critical part of the analysis. For built-in types, PRINTLN () uses exhaustive methods to convert each type to a string for printing. For a more general case, first determine whether the type implements the string () method and, if so, convert it to a string for printing using the string () method. Otherwise, PRINTLN () uses the reflection function to traverse all member variables of the object for printing. Yes, you can also type queries with reflection, see reflect for details. The relevant documentation for the TYPEOF () method. In addition18. Any type assignment to an anonymous struct to any type cannot be removed. The internal properties of each anonymous struct can only be printed in front of the system default string () functionvar any1 interface{}=1var any2 interface{}= "B"var any3 interface{}=struct{x, y string}{"Hello,world", "AAAAA"}FMT. Println (ANY1,ANY2,ANY3)Because any object instance in the go language satisfies the null interface interface{}, interface{} looks like an any type that can point to any object, as follows: var v1 interface{} = 1      // Assign an int type to Interface{}var v2 interface{} = "abc"  //assign a string type to Interface{}var v3 interface{} = &v2     Assign the *interface{} type to Interface{}var v4 interface{} = struct{x int}{1}var v5 interface{} = &struct{x int}{1} When the function can be connected When subjected to arbitrary object instances, we declare it as interface{}, the most typical example being the function of the PRINTXXX series in the standard library FMT, for example: Func Printf (FMT string, args ... interface{}) func Println (args ... interface{}) ... Overall, interface{} is similar to IUnknown in COM, and we're just beginning to know nothing about it, but we can understand it through interface queries and type queries. Because any object instance in the go language satisfies the null interface interface{}, interface{} looks like an any type that can point to any object, as follows: var v1 interface{} = 1      // Assign an int type to Interface{}var v2 interface{} = "abc"  //assign a string type to Interface{}var v3 interface{} = &v2     Assign the *interface{} type to Interface{}var v4 interface{} = struct{x int}{1}var v5 interface{} = &struct{x int}{1} When the function can be connected When subjected to arbitrary object instances, we declare it as interface{}, the most typical example being the function of the PRINTXXX series in the standard library FMT, for example: Func Printf (FMT sTring, args ... interface{}) func Println (args ... interface{}) ... Overall, interface{} is similar to IUnknown in COM, and we're just beginning to know nothing about it, but we can understand it through interface queries and type queries.


The basic summary of Go language surface combination to object programming

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.