Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang array referencing eg. b[1:4] references elements 1,2,3

Tags:

go

The golang blog states :

"A slice can also be formed by "slicing" an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2)."

Can someone please explain to me the logic in the above. IE. Why doesn't b[1:4] reference elements 1 through 4? Is this consistent with other array referencing?

like image 779
brianoh Avatar asked May 03 '11 11:05

brianoh


People also ask

How do you pass an array by reference in Go?

To answer the original question, you can pass a pointer to the array, to pass the array by reference. For example, the following function changes the contents of an array of 3 integers. hence it gives you the error cannot use a (type [100]int) as type *int in argument to f .

What does [:] mean in Golang?

In a nutshell, the [:] operator allows you to create a slice from an array, optionally using start and end bounds.

How do I slice an array in Golang?

creating a slice using make func make([]T, len, cap) []T can be used to create a slice by passing the type, length and capacity. The capacity parameter is optional and defaults to the length. The make function creates an array and returns a slice reference to it.

What is the difference between C arrays and Go slices?

Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.


1 Answers

Indexes point to the "start" of the element. This is shared by all languages using zero-based indexing:

       | 0 | first | 1 | second | 2 | third | 3 | fourth | 4 | fifth | 5 |
[0]   =  ^
[0:1] =  ^ --------> ^
[1:4] =              ^-------------------------------------> ^  
[0:5] =  ^ ----------------------------------------------------------> ^

It's also common to support negative indexing, although Go doesn't allow this:

       |-6 |       |-5 |        |-4 |       |-3 |        |-2 |       |-1 |
       | 0 | first | 1 | second | 2 | third | 3 | fourth | 4 | fifth | 5 |
like image 127
Matt Joiner Avatar answered Nov 29 '22 22:11

Matt Joiner