go for循环下使用return的问题汇总,打印顺序颠倒问题
func main() {
model.DBNew("./conf.toml")
var user []model.CoreGrained
model.DB().Find(&user)
for _, i := range user {
var gg []string
if err := json.Unmarshal(i.Group, &gg); err != nil { //错误写法 正确做法 err := json.Unmarshal(i.Group, &gg) if err != nil {。。。}
fmt.Println(gg) //打印空值
for _, v := range gg {
for _, vv := range strings.TrimSpace(v) {
if vv == 'c' {
fmt.Println("true")
return //注意使用不当造成问题,这个是for循环没完全执行就半路return返回了
}
}
}
}
}
}
问题1:
func main() {
model.DBNew("./conf.toml")
var user []model.CoreGrained
model.DB().Find(&user)
for _, i := range user {
var gg []string
err := json.Unmarshal(i.Group, &gg)
if err != nil {
log.Print(err)
}
fmt.Println(gg) //看这里的顺序
for _, v := range gg {
for _, vv := range strings.TrimSpace(v) {
if vv == 'B' { //不匹配
fmt.Println("true")
return //注意看这里
}
}
}
}
}
运行结果:
/mnt/c/Users/Administrator/AppData/Local/Temp/GoLand/___75go_build_TestPrt_go_linux
[ admin]
[c051d777-5c41-4e7d-9379-2054851803c4]
问题2
func main() {
model.DBNew("./conf.toml")
var user []model.CoreGrained
model.DB().Find(&user)
for _, i := range user {
var gg []string
err := json.Unmarshal(i.Group, &gg)
if err != nil {
log.Print(err)
}
fmt.Println(gg)
for _, v := range gg {
for _, vv := range strings.TrimSpace(v) {
if vv == 'a' { //关键是这里 ,匹配
fmt.Println("true")
return //注意看这里
}
}
}
}
}
/mnt/c/Users/Administrator/AppData/Local/Temp/GoLand/___291go_build_TestPrt_go_linux
[ admin] //只打印一个admin,?执行顺序被颠倒
true
再看下图取消return
问题3
func main() {
model.DBNew("./conf.toml")
var user []model.CoreGrained
model.DB().Find(&user)
for _, i := range user {
var gg []string
err := json.Unmarshal(i.Group, &gg)
if err != nil {
log.Print(err)
}
fmt.Println(gg)
for _, v := range gg {
for _, vv := range strings.TrimSpace(v) {
if vv == 'c' { //匹配
fmt.Println("true")
return //看这里
}
}
}
}
}
/mnt/c/Users/Administrator/AppData/Local/Temp/GoLand/___111go_build_TestPrt_go_linux
[ admin]
[c051d777-5c41-4e7d-9379-2054851803c4]
true
![](https://img2023.cnblogs.com/blog/1280419/202302/1280419-20230202144844562-1930279034.png)
全部被打印
只返回了一个e