So the function basically takes in an interface readch_obj which defines a single read() method that returns a char.
Now, the trick is, the compiler can intelligently recognize that the FILE object has a method with the required signature (char read() ) and that the STRINGIO object also has a method with that required signature and so the compiler automatically tags the FILE object and STRINGIO object as implementing obj_readch and so, either of those objects can be passed in as an argument to readch().
Note: I'm not saying this is how the Go compiler actually works but this is the basic concept from what I understood.
The language doesn't need to allow for adding methods at runtime for this to work.
If the language did have the scaffolding needed to add methods at runtime, then yes, this technique wouldn't work and thats probably the fundamental difference between ducktyping and this (structural subtyping? not sure what it's called).
Sorry, it's that I was reading on my phone and missed your 'most.' Go's structural typing stuff seems pretty cool, but what I was trying to point out was that it can only get most of the way there, not the whole way. In Ruby, for example, I can define singleton methods, and method names based on a dynamically generated string. I'm not sure how a compiler would be able to do stuff like this. At least, not easily.
Then again, I haven't been keeping up with the more recent advances in compiler stuff, so maybe someone has already done this.
Lets say you have a method the sole task of which is to call call .read() on its argument and return a single char.
char readch(obj) { return obj.read(); }
Now, since I have not declared any explicit type for obj, the compiler would generate code like this:
So the function basically takes in an interface readch_obj which defines a single read() method that returns a char.Now, the trick is, the compiler can intelligently recognize that the FILE object has a method with the required signature (char read() ) and that the STRINGIO object also has a method with that required signature and so the compiler automatically tags the FILE object and STRINGIO object as implementing obj_readch and so, either of those objects can be passed in as an argument to readch().
Note: I'm not saying this is how the Go compiler actually works but this is the basic concept from what I understood.
The language doesn't need to allow for adding methods at runtime for this to work.
If the language did have the scaffolding needed to add methods at runtime, then yes, this technique wouldn't work and thats probably the fundamental difference between ducktyping and this (structural subtyping? not sure what it's called).