├── README.md ├── Type Switch Internals.md ├── Method Dispatch - Low Level Detail.md ├── gotchas ├── second-level methods.md ├── COPYING.md └── OOP.md /README.md: -------------------------------------------------------------------------------- 1 | ## Objectives of this repository 2 | 3 | * Ease golang learning by associating golang-specific *concepts* with previously known concepts in the OOP field. 4 | 5 | * ***Promote golang usage*** by easing language understanding for people coming from a heavy OOP background 6 | 7 | ## Golang Concepts 8 | Golang introduces words with a new golang-specific meaning, such as *struct* and *interface*. 9 | This is not bad, but sometimes it is nice to have a "translation" available to be able to understand golang-concepts by relating them to previously known concepts. 10 | 11 | This is important in order to *understand* concepts of a new language. 12 | If you can *translate* a golang-word to previously known concepts, 13 | the learning is by far easier. 14 | 15 | ## Main Document: (start here) 16 | 17 | [Golang Struct and Interface from OOP concepts](OOP.md) 18 | 19 | ## Other Documents 20 | 21 | [Gotchas](gotchas.md) 22 | 23 | [Method Dispatch - Low Level Detail](Method%20Dispatch%20-%20Low%20Level%20Detail.md) 24 | 25 | [Type Switch Internals](Type%20Switch%20Internals.md) 26 | 27 | [Second-Level Methods](second-level%20methods.md) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Type Switch Internals.md: -------------------------------------------------------------------------------- 1 | ### Type Switch 2 | 3 | A golang *Type Switch* has a lot of magic in it. 4 | By using the create and assign syntax (*:=*) inside a *Type Switch* 5 | you're defining and assigning the same var with different types on each case. 6 | 7 | Example from [go-wiki](https://code.google.com/p/go-wiki/wiki/Switch) 8 | 9 | ```go 10 | func do(v interface{}) string { 11 | switch u := v.(type) { 12 | case int: 13 | return strconv.Itoa(u*2) // u has type int 14 | 15 | case string: 16 | mid := len(u) / 2 // split - u has type string 17 | return u[mid:] + u[:mid] // join 18 | 19 | case Stringer: //*another (non-empty) interface* 20 | return u.String() //call via method dispatch 21 | } 22 | return "unknown" 23 | } 24 | 25 | => 26 | do(21) == "42" 27 | do("bitrab") == "rabbit" 28 | do(3.142) == "unknown" 29 | 30 | Pseudo-code 31 | 32 | func do(v interface{}) string 33 | 34 | switch type-in.(v) 35 | 36 | case int: 37 | var u int = value-in.(v) 38 | return strconv.Itoa(u*2) 39 | 40 | case string: 41 | var u string = value-in.(v) 42 | let mid = len(u) / 2 43 | return u[mid:] + u[:mid] 44 | 45 | case Stringer-interface: 46 | var u Stringer-interface = value-in.(v) 47 | return u.String() //call via method dispatch 48 | 49 | return "unknown" 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /Method Dispatch - Low Level Detail.md: -------------------------------------------------------------------------------- 1 | ***This is what I understand happens at low-level when you use interface parameters/vars*** 2 | 3 | ### Golang Interfaces 4 | 5 | A ***golang-Interface*** is ***a class with no fields and ONLY VIRTUAL methods***. 6 | 7 | ```go 8 | type J interface 9 | to-string() ( string ) 10 | dosomea ( x, J ) 11 | dosomeb ( x, k ) (J) 12 | dosomec ( x, a string) ( int ) 13 | ``` 14 | 15 | If a struct *implements* such methods, it “satisfies the interface”. 16 | 17 | You can create a “var of type interface” or declare a function param of type interface. 18 | * a `var x` of type interface is NIL until a *concrete-type* its assigned to it. 19 | * a `var x` of type interface is internally just 2 pointers. One pointer to an ITable and other to the concrete value stored. 20 | 21 | so `var x J-interface` internally is: 22 | 23 | ```go 24 | c-struct interface-var 25 | ITable *ITable 26 | concrete-value any_union 27 | ``` 28 | 29 | an ITable is: 30 | 31 | ```go 32 | c-struct ITable 33 | concrete-type *type 34 | interface-type *interface 35 | jmp-table[] *function 36 | ``` 37 | 38 | 39 | When a concrete type is assigned to a interface-var, golang *creates a jmp-method table on the fly (and caches it). There is a jmp-table for each combination of J-Interface \* concrete-type-implementing-J-interface 40 | 41 | Let’s assume z is struct Z and there is a bunch of functions as *func dosomex ( z ){...}* so that struct Z implements interface J 42 | 43 | When you do: 44 | 45 | ```go 46 | var x J-interface = z 47 | ``` 48 | 49 | golang *constructs the ITable on the fly*. The J-interface has 4 methods, so it needs to calculate x.ITable. Golang will search the method “to-string” of struct Z and put it in ITable.jmp-table[0], then look for “dosomea (struct Z)” and put it in ITable.jmp-table[1] and so on. Then it will store ITable->concrete = &struct-Z, and X.itable->interface= &interface-J”. 50 | 51 | x, being an *interface* type, has two 32bit pointers, the first will point to the newly created ITable “&struct-Z, &interface-J, jmp-table[0...3]” (where the concrete-type-info is stored) and the second points to the concrete-value (in this case a copy of z) 52 | 53 | then… 54 | 55 | ```go 56 | for n:=1; n++<100 { 57 | print( x.dosomea(x)) 58 | } 59 | ``` 60 | 61 | the call *x.dosomea()* is: 62 | * x is var type interface -> struct Z, Interface J 63 | * so x.ITable -> “struct-Z,interface-J,jmp-table[0..3]” 64 | * *x.dosomea()* gets translated to call [x.ITable.jmps[1]] (since “dosomea” => index 1) 65 | * this is a memory fetch and an indirect-call. 66 | * interface values are passed by value, so x.ITable and x.value are always available in the stack. To know the concrete type stored in x.value golang must dereference c.ITable->concrete-type. 67 | 68 | -------------------------------------------------------------------------------- /gotchas: -------------------------------------------------------------------------------- 1 | ## Gotchas 2 | 3 | **Why "flag" package returns pointers or require references?** 4 | 5 | usage: 6 | 7 | ```go 8 | import "flag" 9 | var int_ptr = flag.Int("flagname", 1234, "help message for flagname") 10 | 11 | package flag 12 | func Int(name string, value int, usage string) *int 13 | ``` 14 | 15 | - because they make all the assignments at the flags.Parse() function. 16 | 17 | 18 | **What's exactly an 'Interface'** 19 | 20 | An Interface is a type holding two pointers: 21 | * a pointer to a method table (holding type and method implementations) 22 | * a pointer to a concrete value (the type defined by the method table) 23 | 24 | Ref: 25 | - http://research.swtch.com/interfaces 26 | - http://blog.golang.org/laws-of-reflection 27 | 28 | **Compare Interface to nil** 29 | 30 | Comparing a `var:Interface` to `nil` evaluates to *true* **only if both pointers are 0 (null pointers)** 31 | 32 | **Why is my nil error value not equal to nil?** 33 | http://golang.org/doc/faq#nil_error 34 | 35 | Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3). 36 | 37 | An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil. 38 | 39 | This situation can be confusing, and often arises when a nil value is stored inside an interface value such as an error return: 40 | 41 | ```go 42 | func returnsError() error { 43 | var p *MyError = nil 44 | if bad() { 45 | p = ErrBad 46 | } 47 | return p // Will always return a non-nil error. 48 | } 49 | ``` 50 | 51 | If all goes well, the function returns a nil p, so the return value is an error interface value holding (*MyError, nil). This means that if the caller compares the returned error to nil, it will always look as if there was an error even if nothing bad happened. To return a proper nil error to the caller, the function must return an explicit nil: 52 | 53 | ```go 54 | 55 | func returnsError() error { 56 | if bad() { 57 | return ErrBad 58 | } 59 | return nil 60 | } 61 | ``` 62 | 63 | It's a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as *MyError, to help guarantee the error is created correctly. As an example, os.Open returns an error even though, if not nil, it's always of concrete type *os.PathError. 64 | 65 | Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be nil. For more information, see The Laws of Reflection. 66 | -------------------------------------------------------------------------------- /second-level methods.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | A ***first-level method*** is a method which ***DO NOT CALL *other methods* in the class/struct/interface*** 4 | 5 | A ***second-level method*** is a method which ***DO CALL *other methods* in the class/struct/interface*** 6 | 7 | 8 | 9 | Example, using structs-inheritance by embedding: 10 | 11 | ```go 12 | package main 13 | 14 | import "fmt" 15 | 16 | type parent struct { 17 | } 18 | func (_ parent) simple() { 19 | fmt.Println("parent simple called") 20 | } 21 | func (p parent) complex() { 22 | fmt.Print("in complex, calling simple:") 23 | p.simple() 24 | } 25 | 26 | type child struct { 27 | parent 28 | } 29 | func (_ child) simple() { 30 | fmt.Println("child simple called") 31 | } 32 | 33 | func main() { 34 | var p = parent{} 35 | var c = child{} 36 | 37 | p.simple() 38 | p.complex() 39 | 40 | c.simple() 41 | c.complex() 42 | } 43 | 44 | => 45 | 1 parent simple called 46 | 2 in complex, calling simple: parent simple called 47 | 48 | 3 child simple called 49 | 4 in complex, calling simple: parent simple called //2nd level method was called on base-class context 50 | ``` 51 | 52 | 53 | Here `func Simple` is a first-level method (do not call other struct methods) 54 | and `func Complex` is a second-level method (do call other struct methods) 55 | 56 | Since all the inheritance hierarchy is made by embedding structs, the problem with 2nd level methods is that they're called in the base/parent-class context, so output line 4, where you might expect see "child simple called" is really "parent simple called". This is correct behavior for structs, because all struct-method calls are non-virtual and resolved at compile time. 57 | 58 | 59 | Now the example, but using interfaces: 60 | 61 | ```go 62 | package main 63 | 64 | import "fmt" 65 | 66 | type sampler interface { 67 | simple() 68 | } 69 | 70 | func complex(i sampler) { 71 | fmt.Print("in complex, calling simple:") 72 | i.simple() 73 | } 74 | 75 | type parent struct { 76 | } 77 | 78 | func (_ parent) simple() { 79 | fmt.Println("parent simple called") 80 | } 81 | 82 | type child struct { 83 | parent 84 | } 85 | 86 | func (_ child) simple() { 87 | fmt.Println("child simple called") 88 | } 89 | 90 | func main() { 91 | var p = parent{} 92 | var c = child{} 93 | 94 | p.simple() 95 | complex(p) 96 | 97 | c.simple() 98 | complex(c) 99 | } 100 | 101 | => 102 | 1 parent simple called 103 | 2 in complex, calling simple:parent simple called 104 | 3 child simple called 105 | 4 in complex, calling simple:child simple called 106 | ``` 107 | 108 | Here `func Simple` is a first-level method (do not call other struct methods) 109 | and `func Complex` is a second-level method (do call other *interface* methods) 110 | 111 | Since the inheritance hierarchy of `func simple` and `func complex`is made with an *interface*, the advantage with 2nd level methods 112 | is that they're called *by method dispatch*, so output line 4 has "child simple called". This is correct behavior for *interfaces* because all interface-method calls are virtual so they're resolved *at run time*. 113 | 114 | In the first call to 2nd-level `func complex`, internal call `simple` resolved to Parent_simple. In the second call to `func complex`, internal call `simple` resolved to Child_simple. That's because all interface-method calls are virtual so they're resolved *at run time* 115 | 116 | 117 | 118 | 119 |

Written with [StackEdit](https://stackedit.io/).

120 | -------------------------------------------------------------------------------- /COPYING.md: -------------------------------------------------------------------------------- 1 |

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 2.0 Generic License.

2 | 3 |

4 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL 5 | SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN 6 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON 7 | AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE 8 | INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 9 | ITS USE.

10 | 11 |

License

12 |

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

13 |

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

14 |

1. Definitions

15 |
    16 |
  1. 17 | "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. 18 |
  2. 19 |
  3. 20 | "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. 21 |
  4. 22 |
  5. 23 | "Licensor" means the individual or entity that offers the Work under the terms of this License. 24 |
  6. 25 |
  7. 26 | "Original Author" means the individual or entity who created the Work. 27 |
  8. 28 |
  9. 29 | "Work" means the copyrightable work of authorship offered under the terms of this License. 30 |
  10. 31 |
  11. 32 | "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 33 |
  12. 34 |
  13. "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.
35 |

2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

36 |

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

37 |
    38 |
  1. 39 | to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; 40 |
  2. 41 |
  3. 42 | to create and reproduce Derivative Works; 43 |
  4. 44 |
  5. 45 | to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; 46 |
  6. 47 |
  7. 48 | to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. 49 |
  8. 50 |
  9. For the avoidance of doubt, where the work is a musical composition:

    51 |
      52 |
    1. Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    2. 53 |
    3. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). 54 |
    4. 55 |
    56 |
  10. 57 |
  11. Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
  12. 58 |
59 |

The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

60 |

4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

61 |
    62 |
  1. 63 | You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any reference to such Licensor or the Original Author, as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any reference to such Licensor or the Original Author, as requested. 64 |
  2. 65 |
  3. 66 | You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.0 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License. 67 |
  4. 68 |
  5. 69 | If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and give the Original Author credit reasonable to the medium or means You are utilizing by conveying the name (or pseudonym if applicable) of the Original Author if supplied; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. 70 |
  6. 71 |
72 |

5. Representations, Warranties and Disclaimer

73 |

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

74 |

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

75 |

7. Termination

76 |
    77 |
  1. 78 | This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. 79 |
  2. 80 |
  3. 81 | Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 82 |
  4. 83 |
84 |

8. Miscellaneous

85 |
    86 |
  1. 87 | Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. 88 |
  2. 89 |
  3. 90 | Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. 91 |
  4. 92 |
  5. 93 | If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 94 |
  6. 95 |
  7. 96 | No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. 97 |
  8. 98 |
  9. 99 | This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. 100 |
  10. 101 |
102 | 103 | 104 |

Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor.

105 |

Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, neither party will use the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time.

106 |

Creative Commons may be contacted at https://creativecommons.org/.

107 |
108 | 109 | -------------------------------------------------------------------------------- /OOP.md: -------------------------------------------------------------------------------- 1 | # Golang concepts from an OOP point of view 2 | 3 | ## Introduction 4 | 5 | ### Objectives of this document 6 | 7 | * Ease golang learning by associating golang-specific *concepts* with previously known concepts in the OOP field. 8 | 9 | * ***Promote golang usage*** by easing language understanding for people coming from a heavy OOP background 10 | 11 | ### Why github? 12 | This is a discovery process, I'm writing this document to help myself understand golang and maybe help others. 13 | This document is published in github. **_Pull requests are welcomed_**. There are a lot of things to improve, but please, please do not start a pull request with [*"Technically...*"](http://xkcd.com/1475) 14 | 15 | ## Golang Concepts 16 | Golang introduces words with a new golang-specific meaning, such as *struct* and *interface*. 17 | This is not bad, but sometimes it is nice to have a "translation" available to be able to understand golang-concepts by relating them to previously known concepts. 18 | 19 | This is important in order to *understand* concepts of a new language. 20 | If you can *translate* a golang-word to previously known concepts, 21 | the learning is by far easier. 22 | 23 | ## Cheat Sheet 24 | 25 | |Golang|Classic OOP 26 | |----|-----| 27 | |*struct*|class with fields, only non-virtual methods 28 | |*interface*|class without fields, only virtual methods 29 | |*embedding*|multiple inheritance AND composition 30 | |*receiver*|implicit *this* parameter 31 | 32 | ## Golang-struct is a class (non-virtual) 33 | 34 | A ***golang-struct*** is a ***class*** with ***fields*** where all the methods are ***non-virtual***. e.g.: 35 | 36 | ```go 37 | type Rectangle struct { 38 | Name string 39 | Width, Height float64 40 | } 41 | 42 | func (r Rectangle) Area() float64 { 43 | return r.Width * r.Height 44 | } 45 | ``` 46 | 47 | This can be read as (pseudo code): 48 | 49 | ```go 50 | class Rectangle 51 | field Name: string 52 | field Width: float64 53 | field Height: float64 54 | method Area() //non-virtual 55 | return this.Width * this.Height 56 | ``` 57 | 58 | ### Constructor 59 | 60 | - There is a *zero-value* defined for each core-type, so if you do not provide values at instantiation, all fields will have the zero-value 61 | 62 | - No specific in-class constructors. There is a *generic constructor* for any class instance, receiving a generic literal in a JSON-like format and using reflection to create instances of any class. 63 | 64 | pseudo-code for the generic constructor: 65 | 66 | ```go 67 | function construct ( class, literal) 68 | 69 | helper function assignFields ( object, literal) //recursive 70 | if type-of object is "object" 71 | if literal has field-names 72 | for each field in object.fields 73 | if literal has-field field.name 74 | assignFields(field.value, literal.fields[field.name].value) //recurse 75 | else 76 | //literal without names, assign by position 77 | for n=0 to object.fields.length 78 | assignFields(object.fields[n].value, literal.fields[n].value) //recurse 79 | else 80 | //atom type 81 | set object.value = literal.value 82 | 83 | 84 | // generic constructor main body 85 | var classInstance = new class 86 | assignFields(classInstance, literal) 87 | return classInstance 88 | ``` 89 | 90 | Constructors example: 91 | 92 | ```go 93 | package main 94 | 95 | import . "fmt" 96 | 97 | type Rectangle struct { 98 | Name string 99 | Width, Height float64 100 | } 101 | 102 | func main() { 103 | var a Rectangle 104 | var b = Rectangle{"I'm b.", 10, 20} 105 | var c = Rectangle{Height: 12, Width: 14} 106 | 107 | Println(a) 108 | Println(b) 109 | Println(c) 110 | } 111 | ``` 112 | 113 | Output: 114 | 115 | ``` 116 | { 0 0} 117 | {I'm b. 10 20} 118 | { 14 12} 119 | ``` 120 | 121 | 122 | ## Golang "embedding" is akin to ***multiple inheritance with non-virtual methods*** 123 | 124 | By *embedding* a struct into another you have a mechanism similar to ***multiple inheritance with non-virtual members***. 125 | 126 | Let's call "base" the struct embedded and "derived" the struct doing the embedding. 127 | 128 | After embedding, the base fields and methods are directly available in the derived struct. Internally a *hidden field* is created, named as the base-struct-name. 129 | 130 | Note: The official documents call it "an anonymous field", but this add to confusion, since ***internally there is an embedded field named as the embedded struct***. 131 | 132 | Base fields and methods are directly available as if they were declared in the derived struct, but *base fields and methods* **can be "shadowed"** 133 | 134 | **Shadowing** means defining another field or method *with the same name (and signature)* of a *base* field or method. 135 | 136 | Once shadowed, the only way to access the base member is to use the *hidden field* named as the base-struct-name. 137 | 138 | ```go 139 | type base struct { 140 | a string 141 | b int 142 | } 143 | 144 | type derived struct { 145 | base // embedding 146 | d int 147 | a float32 //-SHADOWS 148 | } 149 | 150 | func main() { 151 | var x derived 152 | 153 | fmt.Printf("%T\n", x.a) //=> x.a, float32 (derived.a shadows base.a) 154 | 155 | fmt.Printf("%T\n", x.base.a) //=> x.base.a, string (accessing shadowed member) 156 | } 157 | ``` 158 | 159 | All base members can be accessed via the *hidden field* named as the base-struct-name. 160 | 161 | It is important to note that all *inherited* methods **are called on the hidden-field-struct**. It means that a base method cannot see or know about derived methods or fields. Everything is non-virtual. 162 | 163 | **When working with structs and embedding, everything is STATICALLY LINKED. All references are resolved at compile time.** 164 | 165 | ### Multiple embedding 166 | 167 | ```go 168 | type NamedObj struct { 169 | Name string 170 | } 171 | 172 | type Shape struct { 173 | NamedObj //inheritance 174 | color int32 175 | isRegular bool 176 | } 177 | 178 | type Point struct { 179 | x, y float64 180 | } 181 | 182 | type Rectangle struct { 183 | NamedObj //multiple inheritance 184 | Shape //^^ 185 | center Point //standard composition 186 | Width, Height float64 187 | } 188 | 189 | func main() { 190 | var aRect = Rectangle{ 191 | NamedObj{"name1"}, 192 | Shape{NamedObj{"name2"}, 0, true}, 193 | Point{0, 0}, 194 | 20, 2.5 195 | } 196 | 197 | fmt.Println(aRect.Name) 198 | fmt.Println(aRect.Shape) 199 | fmt.Println(aRect.Shape.Name) 200 | } 201 | ``` 202 | 203 | This can be read: (pseudo code) 204 | 205 | ```go 206 | class NamedObj 207 | field Name: string 208 | 209 | class Shape 210 | inherits NamedObj 211 | field color: int32 212 | field isRegular: bool 213 | 214 | class Rectangle 215 | inherits NamedObj 216 | inherits Shape 217 | field center: Point 218 | field Width: float64 219 | field Height: float64 220 | ``` 221 | 222 | Example: 223 | 224 | In `var aRect Rectangle`: 225 | 226 | - `aRect.Name` and `aRect.NamedObj.Name` refer to the same field 227 | 228 | - `aRect.color` and `aRect.Shape.color` refer to the same field 229 | 230 | - `aRect.name` and `aRect.NamedObj.name` refer to the same field, but `aRect.NamedObj.name` and `aRect.Shape.NamedObj.name` are **different fields** 231 | 232 | - `aRect.NamedObj` and `aRect.Shape.NamedObj` are the same type, **but refer to different objects** 233 | 234 | 235 | ### Method Shadowing 236 | 237 | Since all ***golang-struct*** methods are ***non-virtual***, ***you cannot override methods*** (you need *interfaces* for that) 238 | 239 | If you have a ***method show()*** for example in ***class/struct NamedObj*** and also define a ***method show()*** in ***class/struct Rectangle***, 240 | ***Rectangle/show()*** will ***SHADOW*** the parent's class ***NamedObj/Show()*** 241 | 242 | As with base class fields, you can use the ***inherited class-name-as-field*** to access the base implementation via dot-notation, e.g.: 243 | 244 | ```go 245 | type base struct { 246 | a string 247 | b int 248 | } 249 | 250 | //method xyz 251 | func (this base) xyz() { 252 | fmt.Println("xyz, a is:", this.a) 253 | } 254 | 255 | //method display 256 | func (this base) display() { 257 | fmt.Println("base, a is:", this.a) 258 | } 259 | 260 | type derived struct { 261 | base // embedding 262 | d int 263 | a float32 //-SHADOWED 264 | } 265 | 266 | //method display -SHADOWED 267 | func (this derived) display() { 268 | fmt.Println("derived a is:", this.a) 269 | } 270 | 271 | func main() { 272 | var a derived = derived{base{"base-a", 10}, 20, 2.5} 273 | 274 | a.display() // calls Derived/display(a) 275 | // => "derived, a is: 2.5" 276 | 277 | a.base.display() // calls Base/display(a.base), the base implementation 278 | // => "base, a is: base-a" 279 | 280 | a.xyz() // "xyz" was not shadowed, calls Base/xyz(a.base) 281 | // => "xyz, a is: base-a" 282 | } 283 | ``` 284 | 285 | ### Multiple inheritance and The Diamond Problem 286 | 287 | Golang solves [the diamond problem](https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem) by *not allowing diamonds*. 288 | 289 | Since ***inheritance (embedded fields)*** include inherited field names in the **_inheriting 290 | class (struct)_**, all *embedded* class-field-names *should not collide*. You must rename fields if there is a name collision. This rule avoids the diamond problem, by not allowing it. 291 | 292 | Note: Golang allows you to create a "Diamond" inheritance diagram, and only will complain when you try to access a parent's class field ambiguously. 293 | 294 | ## Golang *methods* and ***"receivers" (this)*** 295 | 296 | A golang ***struct-method*** is the same as a ***class non-virtual method*** but: 297 | 298 | - It is defined *outside* of the ***class(struct)*** body 299 | - Since it is outside the class, it has an *extra section* before the method name to define the **_"receiver" (this)_**. 300 | - The extra section defines ***this*** as an ***explicit parameter*** (The ***this/self*** parameter is implicit in most OOP languages). 301 | - Since there is such a special section to define **_this (receiver)_**, you can also select a ***name*** for ***this/self***. Idiomatic golang is to use a short var name with the class initials. e.g.: 302 | 303 | Example 304 | 305 | ```go 306 | //class NamedObj 307 | type NamedObj struct { 308 | Name string 309 | } 310 | 311 | //method show 312 | func (n NamedObj) show() { 313 | Println(n.Name) // "n" is "this" 314 | } 315 | 316 | //class Rectangle 317 | type Rectangle struct { 318 | NamedObj //inheritance 319 | Width, Height float64 320 | } 321 | 322 | //override method show 323 | func (r Rectangle) show() { 324 | Println("Rectangle ", r.Name) // "r" is "this" 325 | } 326 | ``` 327 | 328 | Pseudo-code: 329 | 330 | ```go 331 | class NamedObj 332 | Name: string 333 | 334 | method show 335 | print this.Name 336 | 337 | class Rectangle 338 | inherits NamedObj 339 | field Width: float64 340 | field Height: float64 341 | 342 | method show //override 343 | print "Rectangle", this.Name 344 | ``` 345 | 346 | Using it: 347 | 348 | ```go 349 | func main() { 350 | var a = NamedObj{"Joe"} 351 | var b = Rectangle{NamedObj{"Richard"}, 10, 20} 352 | 353 | a.show("Hello") 354 | b.show("Hello") 355 | } 356 | ``` 357 | 358 | Output: 359 | 360 | ``` 361 | Hello I'm Joe 362 | Hello I'm Richard 363 | - I'm a Rectangle named Richard 364 | ``` 365 | 366 | ## Structs vs Interfaces 367 | 368 | A ***golang-Interface*** is ***a class with no fields and ONLY VIRTUAL methods***. 369 | 370 | The *interface* in Golang is designed to complement *structs*. This is a very important "symbiotic" relationship in golang. *Interface* fits perfectly with *structs*. 371 | 372 | You have in Golang: 373 | >**_Structs:_** classes, with fields, ALL NON-VIRTUAL methods 374 | 375 | >**_Interfaces:_** classes, with NO fields, ALL VIRTUAL methods 376 | 377 | By restricting *structs* to non-virtual methods, and restricting *interfaces* to *all-virtual* methods and no fields. Both elements can be perfectly combined by *embedding* to create *fast* polymorphism and multiple inheritance *without the problems associated to multiple inheritance in classical OOP* 378 | 379 | ## Interfaces 380 | 381 | A *golang-Interface* is a ***class, with NO fields, and ALL VIRTUAL methods*** 382 | 383 | Given this definition, you can use an interface to: 384 | 385 | - Declare a var or parameter of type *interface*. 386 | - *implement* an interface, by declaring all the *interface virtual methods* in a *concrete class (a struct)* 387 | - *inherit(embed)* a golang-interface into another golang-interface 388 | 389 | ### Declare a var/parameter with type interface 390 | 391 | By picturing an ***Interface*** as a ***class with no fields and only virtual abstract methods***, you can understand the advantages and limitations of *Interfaces* 392 | 393 | By declaring a var/parameter with type *interface* you define the set of valid methods for the var/parameter. This allows you to use a form of ***polymorphism*** via ***method dispatch*** 394 | 395 | When you declare a var/parameter with type interface: 396 | 397 | - The var/parameter has no fields 398 | - The var/parameter has *a defined set of methods* 399 | - When you call a method on the var/parameter, a *concrete method* is called via *method dispatch* from a jmp-table. (polymorphism via method dispatch) 400 | - When the interface is used as a parameter type: 401 | - You can call the function with *any class* implementing the interface 402 | - The function works for *every class* implementing the interface (the function is polymorphic) 403 | 404 | 405 | *Note on golang implementation*: The *ITables* used for method dispatch are constructed dynamically as needed and cached. Each *class(struct)* has one ITable for each *Interface* the *class(struct) implements*, so, if all *classes(structs)* implement all interfaces, there's a *ITable* for each *class(struct)*-*Interface* combination. See: [Go Data Structures: Interfaces](http://research.swtch.com/interfaces) 406 | 407 | #### Examples from [How to use interfaces in Go](http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go) , with commented pseudo-code 408 | 409 | ```go 410 | package main 411 | 412 | import ( 413 | "fmt" 414 | ) 415 | 416 | /* 417 | class Animal 418 | virtual abstract Speak() string 419 | */ 420 | type Animal interface { 421 | Speak() string 422 | } 423 | 424 | /* 425 | class Dog 426 | method Speak() string //non-virtual 427 | return "Woof!" 428 | */ 429 | type Dog struct { 430 | } 431 | 432 | func (d Dog) Speak() string { 433 | return "Woof!" 434 | } 435 | 436 | /* 437 | class Cat 438 | method Speak() string //non-virtual 439 | return "Meow!" 440 | */ 441 | type Cat struct { 442 | } 443 | 444 | func (c Cat) Speak() string { 445 | return "Meow!" 446 | } 447 | 448 | /* 449 | class Llama 450 | method Speak() string //non-virtual 451 | return "LaLLamaQueLLama!" 452 | */ 453 | type Llama struct { 454 | } 455 | 456 | func (l Llama) Speak() string { 457 | return "LaLLamaQueLLama!" 458 | } 459 | 460 | /* 461 | func main 462 | var animals = [ Dog{}, Cat{}, Llama{} ] 463 | for each animal in animals 464 | print animal.Speak() // method dispatch via jmp-table 465 | */ 466 | 467 | func main() { 468 | animals := []Animal{Dog{}, Cat{}, Llama{}} 469 | for _, animal := range animals { 470 | fmt.Println(animal.Speak()) // method dispatch via jmp-table 471 | } 472 | } 473 | ``` 474 | 475 | ### The empty Interface 476 | 477 | By picturing an ***Interface*** as a ***class with no fields and only virtual abstract methods***, you can understand ***what*** the golang ***Empty Interface: "Interface{}"*** is. 478 | 479 | ***Interface{}*** in golang is a ***class with no fields and no methods*** 480 | 481 | But, since by definition all *classes(structs)* implement ***Interface{}*** it means 482 | that a `var x Interface{}` ***can hold any value*** 483 | 484 | What can you do with a `var x Interface{}`? Well, initially, nothing, because you don't know the type of the concrete value stored inside the `var x Interface{}` 485 | 486 | ***To actually use*** the *value* inside a `var x Interface{}` you must use a [Type Switch](https://golang.org/doc/effective_go.html#type_switch), a *type assertion*, or *reflection* 487 | 488 | There is no automatic type-conversion **from** `Interface{}` 489 | 490 | ## Using struct embedding 491 | 492 | When you use ***only struct embedding*** to create a multi-root hierarchy, via multiple inheritance, you must remember that *all struct methods are non-virtual*. 493 | 494 | That's why a *struct* hierarchy ***is always faster***. When no interfaces are involved, the compiler ***knows*** exactly what concrete function to call, so all calls are direct calls resolved at compile time. Also the functions can be inlined. 495 | 496 | **_The problem is with [second-level methods][1]_**. You cannot alter the execution of a base-class second-level method, because all struct-methods are non-virtual. 497 | You will inherit fields and methods, but methods are always executed on the base-class context. 498 | 499 | **When working with structs and embedding, everything is STATICALLY LINKED. All references are resolved at compile time. There are no virtual methods in structs** 500 | 501 | ## Using interfaces 502 | 503 | When you use ***only interface embedding*** to create a multi-root hierarchy, via multiple inheritance, you must remember that *all interface methods are virtual*. 504 | 505 | That's why a *interface* hierarchy ***is always slower than structs***. When interfaces are involved, the compiler ***does not know*** at compile time, what concrete function to call. It depends on the concrete content of the interface var/parameter, so all calls are ***resolved at run-time via method dispatch***. The mechanism is fast, but not as fast as compile-time resolved concrete calls. Also, with an interface-method call, since the concrete function to call is unknown until run-time, the call cannot be inlined. 506 | 507 | **_The advantage of Interfaces is that: with [second-level methods][1]_**. You can alter the execution of the base-interface second-level method, because all interface-methods are virtual. 508 | Since all calls are made via method-dispatch, methods are executed on the context of the **actual instance**. 509 | 510 | 511 | ## To be continued... 512 | 513 | Drafts: 514 | [Type Switch Internals](Type%20Switch%20Internals.md) 515 | 516 | [1]: second-level%20methods.md 517 | --------------------------------------------------------------------------------