duanan1228 2013-04-19 08:21
浏览 30
已采纳

可以在go中编写“流利的”样式api吗? [重复]

This question already has an answer here:

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?

</div>
  • 写回答

2条回答 默认 最新

  • douzhong3887 2013-04-19 08:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持