LoginSignup
4
4

More than 5 years have passed since last update.

golangでellipsis

Last updated at Posted at 2016-02-01

Goで文字の省略処理(Ellipsis)しようとしたら、初歩的なことで躓いたのでメモ程度に。

結論

ellipsis.go
package main

// Ellipsis a text
func Ellipsis(length int, text string) string {
    r := []rune(text)
    if len(r) > length {
        return string(r[0:length]) + "..."
    }
    return text
}

要点

  • len(string)は鬼門
    • バイト数返す。考えてみたら当然だよね☆
  • string[n:m]は鬼門
    • バイト位置で切る。考えてみたら当z

蛇足

string 系の関数作るときは、func(params..., string)の形に作るとちょっとだけ便利。

text/templateFuncMapにそのまま放り込めたりする。些細だなー!

sample.go
package main

import (
    "bytes"
    "fmt"
    "text/template"
)

func main() {
    var buf bytes.Buffer
    template.New("text").
        Funcs(template.FuncMap{"ellipsis": Ellipse}).
        Parse(`{{.value | ellipsis 5}}`).
        Execute(buf, map[string]string{"value": "みんみんみらくる☆"})
    fmt.Println(buf.String())
}
4
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4