30秒学会 Golang 片段 · 2017年10月10日

30秒学会 Golang 片段 – PadRight

Pads the given string from the end with spaces until the resulting string reaches the given length.

Use fmt.Sprintf() wih an appropriate format specifier to return the formatted value.

代码实现

import "fmt"

func PadRight(s string, l int) string {
    f := "%" + strconv.Itoa(-l) + "v"
    return fmt.Sprintf(f, s)
}

使用样例

PadRight("go", 8) // "go      "