Skip to content

proposal: bytes, strings: add Truncate #56885

@icholy

Description

@icholy

I find myself implementing this function pretty often and I thought it would be decent addition to the standard library.

// Truncate returns the first n runes of s.
func Truncate(s string, n int) string {
	if len(s) <= n {
		return s
	}
	for i := range s {
		if n == 0 {
			return s[:i]
		}
		n--
	}
	return s
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions