前言
VARCHAR是MySQL中常用的數(shù)據(jù)類型,但其單位究竟是字符還是字節(jié)呢?
官方說明
經(jīng)過查閱,MySQL的 官方文檔給出了答案:
4.1及之后的版本,VARCHAR的單位是字符;4.1之前的版本,VARCHAR的單位是字節(jié)。(As of version 4.1, MySQL interprets length specifications in character column definitions in character units. (Before MySQL 4.1, column lengths were interpreted in bytes.) This applies to CHAR, VARCHAR and the TEXT types.)
同時(shí)官方文檔也提到,4.1及之后的版本以UTF-8作為預(yù)定義字符集。(VARCHAR is shorthand for CHARACTER VARYING. NATIONAL VARCHAR is the standard SQL way to define that a VARCHAR column should use some predefined character set. MySQL 4.1 and up uses UTF8 as this predefined character set.)
計(jì)算方法
在 Go 語言中,是不能用 len 函數(shù)來統(tǒng)計(jì)字符串中的字符個(gè)數(shù)的,這是因?yàn)樵?Go 中,字符串是以 UTF-8 為格式進(jìn)行存儲(chǔ)的,在字符串上調(diào)用 len 函數(shù),取得的是字符串包含的 byte 的個(gè)數(shù)。
那么如何在Go語言中獲取字符串中的字符個(gè)數(shù)呢?有下面幾種方法:
- 使用
bytes.Count()統(tǒng)計(jì) - 使用
strings.Count()統(tǒng)計(jì) - 將字符串轉(zhuǎn)換為
[]rune后調(diào)用 len 函數(shù)進(jìn)行統(tǒng)計(jì) - 使用
utf8.RuneCountInString()統(tǒng)計(jì)
測試發(fā)現(xiàn)速度最快的是 utf8.RuneCountInString()