使用 Go,我想将长字符串截断为任意长度(例如用于日志记录)。
const maxLen = 100
func main() {
myString := "This string might be longer, so we'll keep all except the first 100 bytes."
fmt.Println(myString[:10]) // Prints the first 10 bytes
fmt.Println(myString[:maxLen]) // panic: runtime error: slice bounds out of range
}
现在,我可以用一个额外的变量和if语句来解决它,但这似乎很冗长:
const maxLen = 100
func main() {
myString := "This string might be longer, so we'll keep all except the first 100 bytes."
limit := len(myString)
if limit > maxLen {
limit = maxLen
}
fmt.Println(myString[:limit]) // Prints the first 100 bytes, or the whole string if shorter
}
有没有更短/更清洁的方法?
慕村9548890
汪汪一只猫
相关分类