Golang中如何提高代码可读性的字符串换行技巧

Golang中如何提高代码可读性的字符串换行技巧 我想创建一个自定义错误,但它的字符串非常长。

var ErrWrongPatternVars = errors.New("ERROR: Provided values for src and / or dst flags are of wrong pattern: Accepted Values: /org/environment or in case of single app comparison: org/environment/app where source and destination app should be the same")

为了提高代码可读性,在 Go 语言中,拆分上述字符串的惯用方法是什么?


更多关于Golang中如何提高代码可读性的字符串换行技巧的实战教程也可以访问 https://www.itying.com/category-94-b0.html

7 回复

好的。

好的 :slight_smile:

更多关于Golang中如何提高代码可读性的字符串换行技巧的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


multiLineString := `line 1
    line 2
    line 3`

这不一样。我认为他们想要的是类似 C 语言中 "foo" "bar" 这样的语法。

我不了解那个语法。你能解释一下吗?另外,另一种方法是在字符串内部使用 \n 换行符。

我将常量部分提取为变量,然后将它们添加到动态部分。我通常会在多行中构建长消息,最后在 NewError() 函数中使用单个变量。

func main() {
    fmt.Println("hello world")
}

用户不希望有一个跨越多行的字符串,他们希望将一个单行字符串分散到多行代码中,以使代码行宽更窄。

在C语言中,你可以直接关闭并重新打开字符串字面量,如果它们之间只有空白字符,编译器会在编译时将它们连接起来。这使得 "foo" "bar" 等价于 "foobar"

在Go语言中,处理长字符串换行以提高可读性的常用方法有以下几种:

1. 使用字符串拼接(最常用)

var ErrWrongPatternVars = errors.New(
    "ERROR: Provided values for src and/or dst flags are of wrong pattern. " +
    "Accepted Values: /org/environment or in case of single app comparison: " +
    "org/environment/app where source and destination app should be the same")

2. 使用反引号多行字符串

var ErrWrongPatternVars = errors.New(
    `ERROR: Provided values for src and/or dst flags are of wrong pattern.
Accepted Values: /org/environment or in case of single app comparison:
org/environment/app where source and destination app should be the same`)

3. 使用fmt.Sprintf格式化(适合需要变量插入的情况)

var ErrWrongPatternVars = errors.New(fmt.Sprintf(
    "ERROR: Provided values for src and/or dst flags are of wrong pattern. %s" +
    "Accepted Values: /org/environment or in case of single app comparison: %s" +
    "org/environment/app where source and destination app should be the same",
    " ", " "))

4. 使用字符串数组拼接(适合更复杂的场景)

var ErrWrongPatternVars = errors.New(strings.Join([]string{
    "ERROR: Provided values for src and/or dst flags are of wrong pattern: ",
    "Accepted Values: /org/environment or in case of single app comparison: ",
    "org/environment/app where source and destination app should be the same",
}, ""))

5. 实际应用示例

// 方法1:字符串拼接(推荐)
var ErrWrongPatternVars = errors.New(
    "ERROR: Provided values for src and/or dst flags are of wrong pattern. " +
    "Accepted Values: /org/environment " +
    "or in case of single app comparison: org/environment/app " +
    "where source and destination app should be the same")

// 方法2:定义为常量
const wrongPatternMsg = "ERROR: Provided values for src and/or dst flags " +
    "are of wrong pattern. Accepted Values: /org/environment " +
    "or in case of single app comparison: org/environment/app " +
    "where source and destination app should be the same"

var ErrWrongPatternVars = errors.New(wrongPatternMsg)

对于错误消息,推荐使用第一种字符串拼接方法,这是Go社区中最常见的做法,既能保持代码整洁,又能确保错误消息在输出时是单行格式。

回到顶部