zoukankan      html  css  js  c++  java
  • [踩坑]slice引用类型的一个小坑

    大家都知道slice是一个引用类型,废话不多说,上代码

    func test(res [][]int) {
    	res[0] = []int{2,2,2,2}
    	res[1][0] = 3
    }
    
    func main() {
    	res := [][]int{[]int{1,1,1,1},[]int{2,2,2,2}}
    	test(res)
    	fmt.Printf("%#v",res)
    	// out: [][]int{[]int{2, 2, 2, 2}, []int{3, 2, 2, 2}}
    }
    

      

    因为slice是引用类型,所以在函数中的修改也会体现回原宿主

    但,如果你在函数中使用了append,那结果就完全不一样了

    func test(res [][]int) {
    	res = append(res, []int{3,3,3,3})
    	res = append(res, []int{4,4,4,4})
    }
    
    func main() {
    	res := [][]int{[]int{1,1,1,1},[]int{2,2,2,2}}
    	test(res)
    	fmt.Printf("%#v",res)
    	// out: [][]int{[]int{1, 1, 1, 1}, []int{2, 2, 2, 2}}
    }
    

      

    因为append会返回一个新的数组,所以不会体现回原宿主 这里是个坑哦 如果需要在其他函数内涉及到append老老实实用指针吧

    Songzhibin
  • 相关阅读:
    Wireshark——工具
    Wireshark——网络协议
    Wireshark——过滤器
    Wireshark——数据包、着色规则和提示
    Floyd最小环
    有向环覆盖问题
    KM算法
    归并排序
    树状数组
    构造强连通图
  • 原文地址:https://www.cnblogs.com/binHome/p/12862453.html
Copyright © 2011-2022 走看看