Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a 'fluent' style api in go? [duplicate]

Tags:

go

Several other languages have a 'fluent' or chained-invokation style of api, which allows you to do calls like this:

public class CatMap : ClassMap<Cat>
{
  public CatMap()
  {
    Id(x => x.Id);
    Map(x => x.Name)
      .Length(16)
      .Not.Nullable();
    Map(x => x.Sex);
    References(x => x.Mate);
    HasMany(x => x.Kittens);
  }
}

Notable examples include fluent nhibernate, jquery method chaining, etc. It's a common (and I'd say quite well loved) api design pattern.

Problem: The go syntax doesn't seem to support this.

You can do this in go:

var blah = X().Y().Thing().OtherThing()

...but this:

package main

import "n"

func main() {
    n.Log(":D")
    .Example()
    .Example
}

Results in:

> command-line-arguments
> ./app.go:7: syntax error: unexpected .

...basically, because go automatically inserts ;'s at the end of a line.

Anyone know if there's a way around this?

Can you disable the auto-; in a block somehow?

Or is this sort of api just not possible in go?

like image 930
Doug Avatar asked Apr 19 '13 08:04

Doug


1 Answers

You can reformat your code to

func main() {
    n.Log(":D").
    Example().
    Example
}

Putting the period at the end of the line avoids automatic semicolon insertion—it only happens after identifiers, literals or closing parens/braces.

like image 101
amon Avatar answered Sep 30 '22 00:09

amon