企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ### 例子1 * 切片不是引用类型么? 为什么我给number2追加一个元素, number1的值没有改变(容量为10, 追加的时候也没扩容) ![](/D:/%E6%AD%A3%E5%BC%8F%E6%A1%8C%E9%9D%A2/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/book/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/images/QQ%E5%9B%BE%E7%89%8720190115152238.png) * 解答 ![](/D:/%E6%AD%A3%E5%BC%8F%E6%A1%8C%E9%9D%A2/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/book/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/images/QQ%E6%88%AA%E5%9B%BE20190115151340.jpg) ![](/D:/%E6%AD%A3%E5%BC%8F%E6%A1%8C%E9%9D%A2/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/book/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/images/QQ%E6%88%AA%E5%9B%BE20190115152358.jpg) > ### 例子2 * len 才是代表了 slice 的有效元素个数(而不是 cap),只有有效元素才能进行读写。 ![](/D:/%E6%AD%A3%E5%BC%8F%E6%A1%8C%E9%9D%A2/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/book/Golang%E5%B7%A5%E4%BD%9C%E7%AC%94%E8%AE%B0/images/QQ%E5%9B%BE%E7%89%8720190115152535.png) > ### 例子3 ~~~ package main import "fmt" func main() { num1 := make([]int, 0, 10) fmt.Println(num1, len(num1), cap(num1)) num2 := num1[2:3] fmt.Println(num2, len(num2), cap(num2)) } ~~~ * * * ~~~ [] 0 10 [0] 1 8 ~~~ > ### 例子3 ~~~ package main import "fmt" func main() { complexArray1 := [3][]string{ []string{"d", "e", "f"}, []string{"g", "h", "i"}, []string{"j", "k", "l"}, } complexArray2 := complexArray1 //若是修改数组中的切片的某个元素,会影响原数组 complexArray2[0][0] = "a" fmt.Println(complexArray1) fmt.Println(complexArray2) //若是修改数组的某个元素就不会影响原数组 complexArray2[0] = []string{"z", "z", "z"} fmt.Println(complexArray1) fmt.Println(complexArray2) } ~~~ * slice不是为删除而设计的数据结构 ~~~ package main import "fmt" func main() { s := []int{1, 2, 3, 4, 5, 6, 7, 8} //删除元素4 s = append(s[:3], s[4:]...) fmt.Println(s) } ~~~ * * * ~~~ package main import "fmt" func main() { //区间这一块不是很好理解 s1 := make([]int, 0, 5) fmt.Println(s1) s2 := s1[2:5] s2 = s1[2:] //右区间未指定长度按切表的长度填充 s2 = s1[2:6] s2 = s1[5:5] fmt.Println(s2) } ~~~