删除嵌套切片中的元素的不同行为在golang中找到
时间:2024-03-04
浏览:119
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《删除嵌套切片中的元素的不同行为在golang中找到》,聊聊,希望可以帮助到正在努力赚钱的你。
我正在开发一个 golang 项目。我试图从现有切片中维护一个切片,其中我的新切片不包含现有切片元素。我尝试过如下代码:
package main
import (
"fmt"
"reflect"
)
func main(){
savedarr := make(map[string][]int)
newarr := make(map[string][]int)
days := []string{"saturday", "friday", "sunday"}
newspotsarr := []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101}
savedarr["saturday"] = []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101}
savedarr["friday"] = []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101}
for _, day := range days{
newarr[day] = newspotsarr
}
for day, newspots := range newarr{
fmt.println("day", day)
fmt.println("top within loop", newspots)
for _, oldspot := range savedarr[day]{
exists, idx := inarray(oldspot, newspots)
if exists {
newspots = append(newspots[:idx], newspots[idx + 1:]...)
}
}
fmt.println("bottom within loop", newspots)
}
}
func inarray(val interface{}, array interface{}) (exists bool, index int) {
exists = false
index = -1
switch reflect.typeof(array).kind() {
case reflect.slice:
s := reflect.valueof(array)
for i := 0; i < s.len(); i++ {
if reflect.deepequal(val, s.index(i).interface()) == true {
index = i
exists = true
return
}
}
}
return
}
其输出如下:
day saturday top within loop [10 20 30 40 50 60 70 80 90 100 101] bottom within loop [] day friday top within loop [101 101 101 101 101 101 101 101 101 101 101] bottom within loop [101 101 101 101 101 101 101 101 101 101] day sunday top within loop [101 101 101 101 101 101 101 101 101 101 101] bottom within loop [101 101 101 101 101 101 101 101 101 101 101] finalarr map[friday:[101 101 101 101 101 101 101 101 101 101] sunday:[101 101 101 101 101 101 101 101 101 101 101] saturday:[]]
我无法理解它是如何工作的。我期望它的输出应该是这样的:
day saturday Top within loop [10 20 30 40 50 60 70 80 90 100 101] Bottom within loop [] day friday Top within loop [10 20 30 40 50 60 70 80 90 100 101] Bottom within loop [] day sunday Top within loop [10 20 30 40 50 60 70 80 90 100 101] Bottom within loop [10 20 30 40 50 60 70 80 90 100 101] finalArr map[friday:[] sunday:[10 20 30 40 50 60 70 80 90 100 101] saturday:[]]
谁能告诉我它是如何工作的吗? 以及如何实现我想要的输出
解决方案
代码未按预期工作,因为所有 newarr[day] 都具有与 newspotsarr 相同的底层数组。您需要通过创建一个新切片并将数据复制到其中来制作 newsportsarr 的副本:
for _, day := range days {
newArr[day] = make([]int, len(newSpotsArr))
copy(newArr[day], newSpotsArr)
}
演示:https://play.golang.org/p/kv-B9NnKqVd
更新:
go中的slice是一个引用类型。在底层,slice 保留了 3 个东西:len、cap 和 ptr。 ptr 是指向内存(底层数组)的指针。当您运行 newarr[day]=newspotsarr 时,将复制所有三个值,这意味着 newarr[day] 指向与 newspotsarr 相同的基础数组。因此,如果您运行 newspotsarr[0]=-100,所有切片都会看到该更改。
另请参阅:https://blog.golang.org/go-slices-usage-and-internals
今天关于《删除嵌套切片中的元素的不同行为在golang中找到》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
