Skip to content

Instantly share code, notes, and snippets.

@drslump
Last active December 23, 2015 07:09
Show Gist options
  • Save drslump/6599204 to your computer and use it in GitHub Desktop.
Save drslump/6599204 to your computer and use it in GitHub Desktop.
# The API designer (library author) exposes these types
interface ISeek:
def seek(offset as int)
def foo(stream as ISeek):
stream.seek(0)
# The API consumer (library user) wants to use the API but
# doesn't want to (or cannot) use the type hierarchy defined
# by the library author. Perhaps because her types are mandated
# by another library/framework and cannot change them freely.
# In order to ensure some type safety, structural typing can
# be used from the "call site", meaning that the library user
# is the one deciding when to use it instead of more classical
# nominal typing.
# Note: we don't implement ISeek
class MyStream:
def seek(offset as int):
print offset
# Here is the call site, I take advantge of structural typing even
# if the API designer didn't think that I would want to do so when
# she initially implemented the library.
foo(MyStream())
# Note: In this example I assume that structural typing is ubiquitous,
# if a type doesn't match nominally it falls back to check its
# structure to see if the type is compatible, sort of what Go
# does.
# We can *turn on* structural typing explicetely with a custom operator
# if we don't wan't to mess with the nominal typing by default. In this
# example I use the keyword `struct` to signal the compiler to check
# the structure of the type instead of its name. This would allow to
# target specific overloads in the API.
foo(MyStream() struct ISeek)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment