Golang的strings.Split()踩坑记录
作者:酒红 发布时间:2024-02-22 11:34:05
背景
工作中,当我们需要对字符串按照某个字符串切分成字符串数组数时,常用到strings.Split()
最近在使用过程中踩到了个坑,后对踩坑原因做了分析,并总结了使用string.Split
可能踩到的坑。最后写本篇文章做复盘总结与分享
场景
当时是需要取某个结构体的某个属性,并将其按,
切分 整体逻辑类似这样的
type Info struct{
Ids string // Ids: 123,456
}
func test3(info Info){
ids := info.Ids
idList := strings.Split(ids , ",")
if len(idList) < 1 {
return
}
log.Println("ids-not-empty")
// ***
}
当ids = ""
时,控制台打印了 ids-not-empty
,当时百思不得其解,按理来说应该直接走return
这个问题激发了我的好奇心,决定认真排查一下
前置
在排查之前,先大概讲讲 Go 中string
的基本结构
golang的string
它的运行时的数据结构位于reflect.StringHeader
type stringHeader struct {
Data unsafe.Pointer
Len int
}
其中Data
指向数据数组的指针 ,Len
为数组的长度
排查
验证
既然代码中的 if
判断为false
,那么就实际打印一下 isList
的长度看看呢
func test3(info Info){
ids := info.Ids
idList := strings.Split(ids, ",")
log.Printf("idList长度: [%d], idList: [%v]", len(idList), idList)
for index, _ := range idList {
log.Printf("idList[%d]:[%v]", index, idList[index])
}
// ***
}
打印底层信息
好奇心加深,打印一下ids
和idList
的信息
const (
basePrintInfoV3 = "%s 字符串的指针地址:[%v],字符串buf数组地址:[%v] ,Len字段的地址:[%p] ,Len字段值:[%v]"
basePrintInfoV2 = "%s切片的指针地址:[%p],切片数组地址:[%p], Len字段的地址:[%p], Len字段的值:[%v]"
)
func test3(info Info) {
ids := info.Ids
idList := strings.Split(ids, ",")
getStringPtr("ids ", &ids)
getStringSliceAllPtr("idList ", &idList)
// ***
}
func getStringPtr(name string, str *string) {
s2 := (*reflect.StringHeader)(unsafe.Pointer(str))
log.Printf(basePrintInfoV3, name, unsafe.Pointer(str), unsafe.Pointer(s2.Data), unsafe.Pointer(&s2.Len), s2.Len)
}
func getStringSliceAllPtr(name string, s1 *[]string) {
s2 := (*reflect.StringHeader)(unsafe.Pointer(s1))
log.Printf(basePrintInfoV2, name, unsafe.Pointer(&s1), unsafe.Pointer(s2.Data), unsafe.Pointer(&s2.Len), s2.Len)
}
追源码
ids
经过 split
之后的数组和预期的不一样,看来应该是 split
源码有特殊处理了,那追一下源码吧
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
大概读一遍源码能够理清楚genSplit
思路
预先确定s 能够被切分成
n
份创建长度为
n
的数组遍历 s ,将每片数据放入数组中
返回
func genSplit(s, sep string, sepSave, n int) []string {
if n == 0 {
return nil
}
if sep == "" {
return explode(s, n)
}
if n < 0 {
// 计算 s 按照 seq 能被切成多少份
n = Count(s, sep) + 1
}
a := make([]string, n)
n--
i := 0
for i < n {
// 定位 s里的第一个 sep 所在的位置
m := Index(s, sep)
if m < 0 {
break
}
// 放入返回的数组
a[i] = s[:m+sepSave]
// 切割s
s = s[m+len(sep):]
i++
}
a[i] = s
return a[:i+1]
}
那么问题应该出就出在 Count
函数中
跟进看看 count
函数会计算 s
字符串中包含了多少个 subStr
func Count(s, substr string) int {
// special case
if len(substr) == 0 {
return utf8.RuneCountInString(s) + 1
}
if len(substr) == 1 {
return bytealg.CountString(s, substr[0])
}
n := 0
for {
i := Index(s, substr)
if i == -1 {
return n
}
n++
s = s[i+len(substr):]
}
}
Count
中会走 len(substr) == 1
这个逻辑,其中的CountString
计算s
中存在多少个 substr[0]
,当时跟进,返回的结果是0
,这里符合预期 。
再结合 genSplit
中的 n = Count() + 1
我们可以发现,在genSplit
时,预先创建的数组长度就为0 + 1 = 1
! 问题迎刃而解
类似情况
经过查阅,这里再总结一下其他使用strings.Split
可能遇到的坑
s := strings.Split("", "")
fmt.Println(s, len(s)) // [] 0 //返回空数组
s = strings.Split("abc,abc", "")
fmt.Println(s, len(s)) // [a b c , a b c] 7 //返回7个数组元素
s = strings.Split("", ",")
fmt.Println(s, len(s)) // [] 1
s = strings.Split("abc,abc", ",")
fmt.Println(s, len(s)) // [abc abc] 2
s = strings.Split("abc,abc", "|")
fmt.Println(s, len(s)) // [abc,abc] 1
fmt.Println(len("")) // 0
fmt.Println(len([]string{""})) // 1
str := ""
fmt.Println(str[0]) // panic
来源:https://juejin.cn/post/7102663514510065672
猜你喜欢
- 正文 curl,用于发送请求的命令行工具,一个 HTTP 请求客户端(实际上它也可以做 FTP/SCP/TELNET 协议的事情,
- 在布尔索引中,我们将根据 DataFrame 中数据的实际值而不是它们的行/列标签或整数位置来选择数据子集。在布尔索引中,我们使用布尔向量来
- 在你的 Django 应用中,你或许希望根据某字段的值对检索结果排序,比如说,按字母顺序。 那么,使用 order_by() 这个方法就可以
- 理解property和attribute这个要看具体的语境了。不过我们可以从词源的角度来区分一下这两者:property形容词propert
- 本文实例讲述了PHP中Static(静态)关键字功能与用法。分享给大家供大家参考,具体如下:1、什么是static?static 是C++中
- 开通了一个阿里云来玩,记录一下环境搭建的过程运行环境ECS Ubuntu 16.04 64位过程#切换到安装文件夹cd /usr/local
- 字段是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快。下
- 有时候在使用 Python 的时候,想要对一个数字或者字符串进行补零操作,即把「1」变为一个八位数的「00000001」,这个时候可以使用一
- 以下代码可自动登录12306 - 包括输入用户名密码以及自动识别验证码并点击验证码登陆。该源码需要稍作修改:把 username
- python代码运行助手是能在网页上运行python语言的工具。因为python的运行环境在很多教程里都是用dos的,黑乎乎的界面看的有点简
- 先看看:css中class与id的区别及应用表单的name与id其实是同一个意思,都是为了标记对象名称。它们所不同的是:name是Netsc
- 看代码吧~# -*- coding:utf-8 -*- import osimport jsonimport numpy as np #fr
- python-查找特定名称文件并按序号、文件名分行打印输出第1天第2题1.遍历”Day1-homework”目录下文件;2.找到文件名包含“
- 使用Resample函数转换时间序列 一、什么是resample函数?它是Python数据分析库Pandas的方法函数。它主要用于
- 本文实例讲述了python flask框架实现重定向功能。分享给大家供大家参考,具体如下:flask 重定向:from flask impo
- NumPy 是一个Python 库,用于 Python 编程中的科学计算。在本教程中,你将学习如何在 NumPy 数组上以多种方式添加、删除
- 据 Python 软件基金会消息,Python Packaging Authority 和 pip 团队于北美时间11月30日宣布发布 pi
- 在WEB2.0这个词未出现之前,是没有所谓的WEB1.0之说的,那时候的互联网也是没有时代之分的,能上的网站不多,值得上的网站更不多,很多的
- xml文件:country.xml<data><country name="shdi2hajk">
- 如下所示:import time首先导入时间模块在程序开始执行的地方写入:start=time.clock()在程序末尾写入:end=tim