Go (Golang) Tutorial #5 - Arrays & Slices
Summary
TLDRThis video script offers an in-depth tutorial on arrays and slices in Go programming. It explains how to declare and initialize arrays with a fixed length, emphasizing that arrays cannot be resized once created. The script then transitions to slices, which are more flexible and can be appended or shortened. It demonstrates how to create slices, modify their values, append new elements, and create new slices from ranges of existing ones. The tutorial concludes by highlighting the practicality of slices over arrays in most programming scenarios.
Takeaways
- π Arrays in Go are declared with a fixed length and cannot be changed once defined.
- π’ To create an array, use the `var` keyword followed by the array name, square brackets for the length, and the data type inside the brackets.
- π The syntax for initializing an array is `var [3]int{20, 25, 30}` where `[3]int` specifies an array of three integers.
- π« Attempting to add more elements than the declared length of an array will result in an error.
- π You can't change the type of elements in an array once it's declared; all elements must be of the specified type.
- π Shorthand array declaration in Go allows the type to be omitted on the left side of the assignment, as Go infers the type automatically.
- π The length of an array can be obtained using the `len()` function, which returns the number of elements in the array.
- π Slices in Go are more flexible than arrays, allowing the length to be changed, and new elements to be appended.
- π‘ Slices are created without specifying a length in the square brackets and can be manipulated using methods like `append()`.
- π Slice ranges allow you to create new slices from a portion of an existing slice, using a start and end index.
- β You can append to a slice range, effectively extending the range with new elements.
Q & A
How do you declare an array in Go?
-You declare an array in Go by using the 'var' keyword followed by the array name, square brackets to specify the length of the array, and the type of elements it will hold. For example, 'var ages [3]int' declares a fixed-length array named 'ages' with three integer elements.
What is the difference between square brackets and curly braces when initializing an array in Go?
-Square brackets are used to declare the length of the array, while curly braces are used to initialize the values of the array. For example, 'var ages [3]int = [20, 25, 30]' uses square brackets to define the array length and curly braces to set the initial values.
Can you change the length of an array in Go once it's declared?
-No, the length of an array in Go is fixed and cannot be changed after it has been declared.
How do you assign a value to an array in Go without explicitly typing it on the left-hand side?
-You can use shorthand assignment by using a colon equal sign (':=') which allows Go to infer the type automatically. For example, 'ages := [3]int{20, 25, 30}' assigns the value without explicitly typing 'int' on the left-hand side.
How do you print the length of an array in Go?
-You can print the length of an array using the 'len' function. For example, 'fmt.Println(len(ages))' will print the length of the 'ages' array.
What is a slice in Go and how is it different from an array?
-A slice in Go is a more flexible, dynamically-sized view into the elements of an array. Unlike arrays, slices do not have a fixed length and can be easily modified, such as appending new elements.
How do you create a slice in Go?
-You create a slice by using square brackets to indicate the type of elements and curly braces to initialize the values without specifying the length, like so: 'scores := []int{150, 60}'.
How do you change the value of an element in a slice?
-You can change the value of an element in a slice by specifying the index of the element and assigning it a new value. For example, 'scores[2] = 25' changes the third element of the 'scores' slice to 25.
How do you append a new element to a slice in Go?
-You use the 'append' function to append a new element to a slice. For example, 'scores = append(scores, 85)' appends the integer 85 to the 'scores' slice.
What are slice ranges and how do you create them?
-Slice ranges allow you to create a new slice from a portion of an existing slice. You create them by specifying the start and end indices within the brackets, like 'range1 := names[1:3]' which creates a new slice containing elements from index 1 to 2 of the 'names' slice.
How do you append a slice with a range of elements from another slice?
-You can append a range of elements from one slice to another by using the 'append' function. For example, 'range1 = append(range1, "cooper")' appends the string 'cooper' to the 'range1' slice.
Outlines
π Introduction to Arrays and Slices in Go
The paragraph introduces arrays and slices in Go programming language. It explains how to declare an array with a fixed length by using the 'var' keyword followed by the array name and type within square brackets. The length of the array is specified before the type. The array is then initialized with values enclosed in curly braces. It's emphasized that once an array's length is set, it cannot be changed, unlike slices. The paragraph also demonstrates how to use shorthand assignment to declare an array without explicitly stating the type on the left side, as Go can infer it. The 'fmt.Println' function is used to print the array and its length using the 'len' function. An example of declaring and printing an array of integers named 'ages' is provided, followed by an example of declaring and printing an array of strings named 'names'.
π Manipulating Slices and Arrays in Go
This paragraph delves into the differences between arrays and slices in Go. While arrays have a fixed length, slices are more flexible and can be modified. The paragraph demonstrates how to create a slice without specifying a length, which automatically creates a slice with a dynamic size. It shows how to change the value of an element within both an array and a slice. The 'append' function is introduced to add elements to a slice, with an example of appending the value '85' to a slice named 'scores'. It's clarified that 'append' returns a new slice, and the original slice variable must be reassigned to this new slice to reflect the change. The paragraph concludes with an explanation of how to print the modified slice and its length, showcasing the updated values and the increased length due to the appended element.
π Understanding Slice Ranges and Appending
The final paragraph focuses on slice ranges, which allow for the extraction of a subset of elements from an existing slice or array. It explains how to create a slice range using a colon notation within square brackets. Examples are provided to demonstrate how to create ranges that start from a specific index and go up to, but not including, another index. The concept of inclusive and exclusive indices in slice ranges is clarified. The paragraph also shows how to append values to these slice ranges, treating them as slices themselves. An example is given where the name 'cooper' is appended to a range named 'range one', and the updated range is printed to confirm the addition. The paragraph concludes by summarizing that while slices and arrays are used differently, slices are more commonly used due to their flexibility, but arrays may still be necessary for certain use cases.
Mindmap
Keywords
π‘Arrays
π‘Slices
π‘Fixed Length
π‘Type Declaration
π‘Curly Braces
π‘Shorthand Declaration
π‘Length Method
π‘Append Function
π‘Range
π‘Type Safety
Highlights
Introduction to arrays and slices in Go programming language.
How to declare an array variable in Go with a specific length and type.
Arrays in Go have a fixed length and cannot be changed once declared.
Demonstration of initializing an array with integer values.
Error handling when trying to add more elements than the array's declared length.
Type enforcement in arrays, where all elements must be of the declared type.
Shorthand method for declaring arrays without explicitly typing on the left-hand side.
Printing an array and its length using the 'fmt.Println' function and 'len' method.
Creating and initializing a string array with shorthand assignment.
Changing the value of an element in an array.
Introduction to slices as a more flexible alternative to arrays.
How to create a slice without specifying a length, unlike arrays.
Modifying the value of an element in a slice.
Appending elements to a slice using the 'append' function.
Explanation of how 'append' returns a new slice and requires assignment to update.
Printing a slice and its length to demonstrate the effects of appending.
Introduction to slice ranges and how to create them from existing arrays or slices.
Demonstration of creating a slice range that includes elements from position 1 to 3.
Explanation of slice range inclusivity and exclusivity of start and end positions.
Creating a slice range from position 2 to the end of the array or slice.
Creating a slice range from the start to position 3, excluding position 3.
Appending to a slice range, which is possible because ranges are essentially slices.
Summary of the differences between arrays and slices in Go, emphasizing the fixed length of arrays and the flexibility of slices.
Transcripts
all right then so i want to move away
now from strings and numbers
and onto two different types arrays and
slices so we'll start with arrays then
go on to slices
so how do we create an array how do we
declare an array variable
well the same way as we would any other
variable so we'd say var
give it a name ages and if we want to
explicitly type this we can do
using square brackets first of all to
signify this is going to be an array
inside the square brackets we see how
many items are going to be in the array
so the length if you like
so if i want three items inside it it's
going to be three
and then we say what type of data is
going to be inside
the array so this now says the ages will
be an array of three items
and they're all going to be ins inside
that array
so if we want to give this a value we
can do we set it equal to something
now we also have to kind of put the
typing
on the right hand side of this
expression as well
so this thing right here we also have to
put
on the right before we actually create
the array
and that might seem a little bit weird
but this is just the way we work in
go and then the array itself is
curly braces not square brackets curly
braces
and then inside that i can add the items
so 20
25 and 30. so these are all ins
and there's now three of these inside
the array as
we say right here now if i try to add in
a fourth
then it's not going to let me you see
this error because we've gone out of the
length
of this declared length right here
so an array unlike other programming
languages you might be
familiar with like python or javascript
has to be
fixed length we can't ever change the
length of an array
once it's been declared it has to have a
specific
length so we're going to move on to
something called slices later which
might feel a bit more like
a raise as you're used to where you can
change the length but for now just know
that an array in go
has a fixed length and it can't change
all right so let me delete this
if i try to add a type in here instead
of an integer
for example a string then it's not going
to let me do that either all right so
these all have to be
integers because we said right here
they're integers
all right then so if we want to do a
shorthand
let me comment this out we can do and in
fact i'm just going to copy this
and then down here i'm going to say var
ages is equal to
and then just paste this in so this is
the same
as this so we don't have to type it on
the left
go just infers the type automatically
for us okay but we still have to do this
on the right hand side of this
assignment
all right then so let me down here print
out the ages i'm going to say
fmt dot print line
and then inside there i'm going to print
out the ages
now we can also print out the length of
an array and the way we do that is by
using the built-in
length method or len and then inside
that we pass in
the array we want the length of so we
want the length of
ages so if i save this and run the file
then we should see the length and the
array itself
so there's the array and there's the
length awesome
let's do another example and this time
i'm going to use the
shorthand assignment so i'm going to say
names is colon equal
to and this time it's going to be square
brackets
and inside that i'll place a four to say
there's gonna be four elements
they're gonna be of type string and then
inside the curly braces we'll do some
names
so yoshi and then mario
and then peach and then
bowser alright so there's our names
array
i'm going to do the same thing as we did
for ages so
let me duplicate this type in names
and then names right here as well and
then i'm going to run this file
and we can see right here the ages and
also now the names and the length of
names awesome so that is arrays and
remember
the length is fixed so now i want to
talk about
slices and slices are more like
typical arrays from other languages
where we can't
change the length we can add items to it
or we can take items away from it
so i'm going to say right here slices
and by the way they use
arrays under the hood all right so
they still use the array type under the
hood but we can manipulate a slice a bit
more
so what i'm going to do is create a new
slice called scores
and i'm going to set it equal to square
brackets
and then i'll say the type inside this
slice and then i'm going to do
curly braces and then i'll just place in
some integers so
150 and 60. and
notice this time i've not placed a
number inside the square brackets
so when i don't do this it creates a
slice for me
not an array a fixed length so
it's pretty much the same other than
that we just don't put a number in here
so what if i want to change the value of
one of these things
well i can do that and in fact let me go
back to arrays because we can also
change the values of arrays as well if i
say for example
names and then we want one that's
position one and it starts at zero
zero one if i wanna set that to be
something else i can't i can set it
equal to
luigi that's going to change this to
luigi i can also do that for slices
so i can say scores and then position
two so that's zero one
two this one and i can set it equal to
something else like 25
all right now i can also now append
items to this slice i can't do that to
an array but i can to a slice
so if i want to append something i say
append
and then in parentheses what
slice i want to append to well that is
the scores one
and then what is the element i want to
append to it well i'll add on
an 85. now this
function right here doesn't actually
change
this scores variable what it does is
return
a new slice for us so if we want to
update this with the new slice we have
to say
scores is now equal to append
scores85 does that make sense because
automatically it doesn't append it it
just returns a new slice
and then that new slice is being
assigned to scores so we're kind of
overwriting
this variable with a new slice so
now let's try printing this out i'm
going to say fmt dot
print line and we're going to print
scores
and the length of scores
so if i run this file now then we should
see
first of all that this element has
changed
from mario to luigi and we can see that
right here
so we get luigi instead of mario and
then down here where we output the
scores we have the extra value 85
and the length which is now four not
three as we first
initialized it all right so
that is slices and that is arrays
there's one more thing i want to talk
about
and that is slice ranges
so a range is a way to get a range of
elements from an existing
rayoff slice and store them in a new
slice
so what i'm going to do is say range 1
is colon equal
2 and remember we use colon equal when
we're first
initializing a variable we set that
equal to
names and then in square brackets i'm
going to say go from position 1
2 3. now what i'm going to do is just
print this out fmt dot print line
and i'm gonna output range one like so
now if i come down here and i run this
we're gonna see this range
and it's luigi and peach so if we take a
look at this remember we
replaced position one with luigi which
is why we get luigi
so that's position one and that's where
we're going from so it includes position
one
up to position three so one two
three but it doesn't include position
three
so it just gets one including this two
three but not including three so we end
up with these two
right here which is why we get them down
here all right
so it's inclusive of the first number
but not of the second
so let me do another range i'm going to
say range
2 colon equal to names
and then this time i'm going to say go
from position 2 colon
and then just leave it at that and what
that does is say okay we'll just go to
the
end of the array or the slice and get me
everything
up until the end so let me output this
right here range
two and see what happens save it and run
it
and we can see we get peach and bowser
so
from position two so zero one two
up until the end including the end one
that's what this does
all right so let me say now range
three is colon equal to names
and then this time it's gonna be colon
three so this but the opposite way
around
so this means go from the start and get
me up to position three but not
including position three
so we'll say range three right here just
to see if this works
spell this correctly and save it
so let's run the file and now we can see
yoshi luigi and peach so from the very
first position
up to position three because we don't
include the third one this is zero
one two we don't include the third one
all right
cool so that is ranges in a nutshell and
we can
append these ranges as well because at
the end of the day they're just
slices so i could say range one is equal
to
append and then we're going to take
range one
and append cooper like so
and then we can just print this out so
i'm going to say
fmt dot print line
and then output range one
like so run this again and we should see
that
range one now has cooper at the end of
it all right
so there we go my friends that is arrays
the length of arrays cannot change and
slices and the length of slices
can change and we can get ranges from
existing arrays and store them in new
slices
now most of the time you'll probably use
a slice instead of an array
but there might be times when you use
these as well
5.0 / 5 (0 votes)