logoalt Hacker News

tineslast Friday at 4:43 PM3 repliesview on HN

I'm not a Go expert but that's exactly what interfaces are, aren't they? In Go a struct automatically implements an interface if it contains all the required fields (duck-typing).


Replies

sparkielast Friday at 5:28 PM

They're both a form of structural typing - the static equivalent of duck typing.

A difference with row types is that they don't have to be declared up front like an interface - they're basically anonymous types. You declare the row types in the type signature.

For example, a function taking some structural subtype of `Foo` and returning some structural subtype of `Bar` would be written in Go as:

    type Foo interface {
        baz Baz
    }
    
    type Bar interface {
        qux Qux
    }
    
    func (x Foo) f() Bar {
        ...
    }
In OCaml, you'd just inline the row types - there are no `Foo` or `Bar`:

    val f : < baz : Baz.t; .. > -> < qux : Qux.t; .. > 
    let f x = ...
You can typedef row types though

    type foo = < baz : Baz.t; .. >
    type bar = < qux : Qux.t; .. >
    val f : foo -> bar
Rows can be declared to have an exact set of members. For example, the types `< bar : Baz.t >` and `< bar : Baz.t; ..>` are two different types. The latter can have members besides `bar`, but the former can only have the member `bar`. A type containing the fields `bar` and `qux` would be a subtype of `< bar : Bar.t; .. >`, but it would not be a subtype of `< bar : Bar.t >`.

OCaml has another form of structural typing in its module system, closer to interfaces where a `module type` is declared up-front, and can be specified as the argument for a functor (parameterized module) - but this is incompatible with the row types in the object system.

show 1 reply
aatd86last Friday at 9:55 PM

It's not fields but methods.