安全なtruncate string - golang

2020-06-28

package main

import (
	"fmt"
)

// Truncate string.
func TruncateString(str string, length int) string {
    if length <= 0 {
        return ""
    }

    // This code cannot support Japanese
    // orgLen := len(str)
    // if orgLen <= length {
    //     return str
    // }
    // return str[:length]

    // Support Japanese
    // Ref: Range loops https://blog.golang.org/strings
    truncated := ""
    count := 0
    for _, char := range str {
	truncated += string(char)
        count++
        if count >= length {
            break
        }
    }
    return truncated
}

// Main
func main() {
	dataList := [][]interface{} {
		{"drink", 3, "dri"},
		{"drink", 6, "drink"},
		{"drink", 0, ""},
		{"drink", -1, ""},
		{"drink", 100, "drink"},
		{"pub", 100, "pub"},
		{"こんにちは", 3, "こんに"},
	}
	for _, dl := range dataList {
		r := TruncateString(dl[0].(string), dl[1].(int))
		if r != dl[2].(string) {
			fmt.Printf("ERROR: got=%s, want=%s", r, dl[2].(string))
		}
	}
}

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

Reference:
https://play.golang.org/p/EzvhWMljku

次のコードはエラーが出る。

package main

import (
	"fmt"
)

func main() {
	s := "drink"
	r := s[:20] // error
	fmt.Println(r)
}

https://play.golang.org/p/7IfclYXADoW