@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Go で chomp (末尾の改行文字を取り除く)

strings.TrimSuffix() を使う。

strings.TrimSuffix(s, "\n")
s := " hello, world!\n"
fmt.Printf("%#v\n", strings.TrimSuffix(s, "\n"))
//=> " hello, world!"

https://golang.org/pkg/strings/#TrimSuffix

TrimRight()\n だけを取り除くのであれば同じだが、 TrimSuffix を使う方が適切らしい。

s := " hello, world!\n"
fmt.Printf("%#v\n", strings.TrimRight(s, "\n"))
//=> " hello, world!"

https://golang.org/pkg/strings/#TrimRight

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

To remove a suffix, use TrimSuffix instead.

TrimSpace() は文字列の両端の空白文字を取り除く。

s := " hello, world!\n"
fmt.Printf("%#v\n", strings.TrimSpace(s))
//=> "hello, world!"

https://golang.org/pkg/strings/#TrimSpace


Ruby との対比表を作るならこんな感じ

Ruby String#chomp String#rstrip String#strip
Go strings.TrimSuffix(s, "\n") strings.TrimRight(s, " \t\r\n\f\v\0") strings.TrimSpace(s)

実験結果

https://play.golang.org/p/CQfFcqK9hwt