Help us understand the problem. What is going on with this article?

golangでellipsis

More than 3 years have passed since last update.

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())
}
kyoh86
Golangとzshとvimをこよなく愛するふとっちょプログラマーです。
https://kyoh86.dev/
wacul
人工知能でWebサイトの課題を発見する AIアナリスト https://wacul-ai.com を開発しています
https://wacul.co.jp
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした