写长语句,分多行书写。

huangapple go评论90阅读模式
英文:

Write long statement in multiple lines

问题

我有一个相当长的func声明,我想将其拆分成几行:

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3) (param4 *Type1, param5 *Type2, param6 *Type3) {
    ...
    return
}

这样写起来相当难以管理。

有没有一种方法可以将函数声明写成以下形式?

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3)
    (param4 *Type1, param5 *Type2, param6 *Type3)
{
    ...
    return
}
英文:

I have a quite long func declaration that I would like to split into several lines:

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3) (param4 *Type1, param5 *Type2, param6 *Type3) {
    ...
    return
}

it is quite unmanageable.

Is there a way of writing a function declaration as follows?

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3)
    (param4 *Type1, param5 *Type2, param6 *Type3)
{
    ...
    return
}

答案1

得分: 4

这是分号插入规则的结果:http://golang.org/ref/spec#Semicolons。Go会自动在第一行的末尾插入一个分号:

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3);
    (param4 *Type1, param5 *Type2, param6 *Type3) {

带有分号的第一行实际上是一个有效的Go表达式:它是一个外部函数。然后,它尝试解析第二行并失败了!

你可以通过两种方式来修复它,一种是将开括号保留在第一行:

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3) (
    param4 *Type1, param5 *Type2, param6 *Type3) {
}

或者在第一行保留一个逗号:

func LongMethodName(param1 *Type1, param2 *Type2,
    param3 *Type3) (param4 *Type1, param5 *Type2, param6 *Type3) {
}

这两种方式在gofmt中都是有效的。

英文:

This is a result of the semicolon insertion rule: http://golang.org/ref/spec#Semicolons. Go automatically inserts a semicolon right at the end of the first line:
<!-- language: lang-go -->

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3);
    (param4 *Type1, param5 *Type2, param6 *Type3) {

The first line with the semicolon is actually a valid go expression: It's an external function. Then, it tries to parse the second line and fails!

You can wrap it either by keeping the opening parenthesis on the first line:
<!-- language: lang-go -->

func LongMethodName(param1 *Type1, param2 *Type2, param3 *Type3) (
    param4 *Type1, param5 *Type2, param6 *Type3) {
}

or by keeping a comma on the first line:
<!-- language: lang-go -->

func LongMethodName(param1 *Type1, param2 *Type2,
    param3 *Type3) (param4 *Type1, param5 *Type2, param6 *Type3) {
}

Both are valid in gofmt.

huangapple
  • 本文由 发表于 2014年7月5日 08:36:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/24581974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定