Skip to content

Instantly share code, notes, and snippets.

@chardos
Last active January 22, 2019 02:06
Show Gist options
  • Save chardos/f11ace8530c1235de151812ab57bdc51 to your computer and use it in GitHub Desktop.
Save chardos/f11ace8530c1235de151812ab57bdc51 to your computer and use it in GitHub Desktop.
// in github.com/chardos/leftpad/leftpad.go
package leftpad
import (
"strings"
"unicode/utf8"
)
// This variable name is lowercase, so it's package-visible
var default_char = ' '
// Format takes in a string and an int and returns the string
// left-padded with spaces to the length of the int. If the
// string is already longer than the specified length, the
// original string is returned.
// This variable name starts with a capital and hence is public
func Format(s string, size int) string {
return FormatRune(s, size, default_char)
}
// FormatRune takes in a string, an int, and a rune and returns the string
// left-padded with the specifed rune to the length of the int. If the
// string is already longer than the specified length, the
// original string is returned.
func FormatRune(s string, size int, r rune) string {
l := utf8.RuneCountInString(s)
if l >= size {
return s
}
out := strings.Repeat(string(r), size-l) + s
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment