English 中文(简体)
一小片谷歌的指数化何时会发生?
原标题:When indexing will happen for a slice in golang?

I am doing some experiments on the slice, When i assign value to a slice with in the length range, it worked fine But when i assign value to a slice with in the cap range without append() func, it gave me runtime error.

Eg: mySlice := make([]int, 3, 5) mySlice[3] = 4 // runtime error

If capacity in make function means, the total space already been allocated for the slice. Then, why i am not able to access that location with indexing?? Why only we can store values using append() func only, if we want to assign value more than length range specified but in the cap range??

package main

import "fmt"

func main() {
    mySlice := make([]int, 3, 5)
    mySlice[0] = 1
    mySlice[1] = 2
    mySlice[2] = 3
    mySlice[3] = 4  `This giving me error saying that "index out of range [3] with length 3"`    
    fmt.Println("mySlice....", mySlice)
}
问题回答

切片的长度是它所含元素的数量。

切片的容量是底部数组中元素的数量,从切片的第一个元素中计算。

您在下面的调用中定义了 len = 3, cap = 5 的切片。

make([]int, 3, 5)

所以,这就是为什么 < code> myClice[3] = 4 = 4 超出范围。 您可以打印切片的长度和容量来检查这一点 。

fmt.Printf("len=%d cap=%d", len(mySlice), cap(mySlice))
//len=3 cap=5

另一方面,附加函数将增长切片, 您可以检查此 < a href=" https:// go. dev/ blog/ slices- intro" rel= " no follown noreferrer" >slips intro documents 。 因此, 您可以毫无错误地使用 < code> 附录

mySlice = append(mySlice, 4)
//len=4 cap=5




相关问题
adding an index to sql server

I have a query that gets run often. its a dynmaic sql query because the sort by changes. SELECT userID, ROW_NUMBER(OVER created) as rownumber from users where divisionID = @divisionID and ...

Linq to SQL nvarchar problem

I have discovered a huge performance problem in Linq to SQL. When selecting from a table using strings, the parameters passed to sql server are always nvarchar, even when the sql table is a varchar. ...

TableView oval button for Index/counts

Can someone help me create an index/count button for a UITableView, like this one? iTunes http://img.skitch.com/20091107-nwyci84114dxg76wshqwgtauwn.preview.jpg Is there an Apple example, or other ...

Move or copy an entity to another kind

Is there a way to move an entity to another kind in appengine. Say you have a kind defines, and you want to keep a record of deleted entities of that kind. But you want to separate the storage of ...

热门标签