4
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Organization

golangでellipsis

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())
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
4
Help us understand the problem. What are the problem?