Go (Golang) Tutorial #5 - Arrays & Slices

Net Ninja
24 May 202110:56

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

00:00

📊 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'.

05:02

🔍 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.

10:03

🔄 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

Arrays in the context of the video refer to a fixed-size data structure that can hold a collection of elements of the same type. The video explains how to declare an array in Go by specifying the type and length using square brackets, followed by the variable name. For instance, 'var ages [3]int' declares an array named 'ages' with a fixed length of 3 and elements of type int. Arrays are a fundamental concept in programming, allowing for the organization and manipulation of multiple items in a single variable. The video emphasizes that in Go, once an array is declared, its length cannot be changed, which is a key characteristic distinguishing it from other data structures like slices.

💡Slices

Slices are a more flexible version of arrays in Go, allowing for dynamic resizing. The video introduces slices as a way to handle sequences of elements similar to arrays but without a fixed size. Slices are created without specifying a length, as shown with 'var scores []int', which initializes a slice of integers. The video demonstrates how slices can be modified by changing individual elements or by appending new elements to the end, using the 'append' function. Slices are a core concept in Go for handling variable-length collections and are often preferred over arrays due to their flexibility.

💡Fixed Length

The term 'fixed length' in the video refers to the immutability of the size of an array once it is declared. This is a key characteristic of arrays in Go, as opposed to slices, which can grow or shrink as needed. The video illustrates this by showing that attempting to add a fourth element to an array of three integers results in an error, highlighting the rigid nature of array sizes in Go. This concept is crucial for understanding the limitations and use cases of arrays compared to other data structures.

💡Type Declaration

Type declaration in Go is the process of specifying the data type of a variable when it is created. The video demonstrates how to declare the type of an array or slice, using square brackets to indicate the array's fixed size and the type of elements it will hold, such as 'int'. This is essential for ensuring that the correct type of data is stored in the array or slice and helps the Go compiler enforce type safety. The video shows that type declaration is mandatory for arrays but can be inferred for slices using the shorthand declaration.

💡Curly Braces

In the context of the video, curly braces are used to initialize the values of an array or slice. Unlike square brackets which define the type and size, curly braces are used to enclose the actual elements, such as '{20, 25, 30}' for an array of integers. This syntax is a standard way in Go to define the initial values of an array or slice, and it is a visual cue that the programmer is specifying the contents of the data structure.

💡Shorthand Declaration

Shorthand declaration is a feature in Go that allows the type of a variable to be inferred by the compiler, simplifying the syntax when declaring variables. The video shows how this can be used with slices, where the type can be omitted on the left side of the assignment, as in 'names := []string{"Yoshi", "Mario", "Peach", "Bowser"}'. This feature makes the code more concise and easier to read, while still maintaining type safety.

💡Length Method

The 'len' function in Go is used to determine the number of elements in an array or slice. The video demonstrates how to use 'len' by passing the array or slice as an argument to retrieve its length. This is important for understanding the size of a data structure and is a common operation when working with collections of data. For example, 'len(ages)' would return the number of elements in the 'ages' array, which is a fixed value due to the nature of arrays.

💡Append Function

The 'append' function in Go is used to add elements to a slice, as slices can be dynamically resized. The video explains that 'append' does not modify the original slice but instead returns a new slice with the additional element. For example, 'scores = append(scores, 85)' adds the number 85 to the 'scores' slice. This is a fundamental operation when working with slices, allowing for the expansion of data structures as needed.

💡Range

A range in Go is a way to specify a subset of elements from an existing array or slice. The video describes how to create a new slice by specifying a range of indices, using a colon to separate the start and end points, as in 'range1 := names[1:3]'. This creates a new slice containing elements from index 1 to 2 (since ranges are inclusive of the start and exclusive of the end). Ranges are a powerful feature for extracting parts of a collection without modifying the original data structure.

💡Type Safety

Type safety in Go refers to the language's ability to check the types of variables at compile time to prevent type-related errors. The video emphasizes type safety by showing how arrays and slices require explicit type declarations, ensuring that only compatible types are stored and manipulated. This feature helps prevent runtime errors and makes the code more robust and predictable, as demonstrated by the video's examples where the type of elements in an array or slice must be consistent.

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

play00:02

all right then so i want to move away

play00:03

now from strings and numbers

play00:05

and onto two different types arrays and

play00:08

slices so we'll start with arrays then

play00:11

go on to slices

play00:12

so how do we create an array how do we

play00:14

declare an array variable

play00:16

well the same way as we would any other

play00:18

variable so we'd say var

play00:20

give it a name ages and if we want to

play00:22

explicitly type this we can do

play00:24

using square brackets first of all to

play00:26

signify this is going to be an array

play00:28

inside the square brackets we see how

play00:30

many items are going to be in the array

play00:32

so the length if you like

play00:34

so if i want three items inside it it's

play00:36

going to be three

play00:37

and then we say what type of data is

play00:39

going to be inside

play00:40

the array so this now says the ages will

play00:43

be an array of three items

play00:45

and they're all going to be ins inside

play00:47

that array

play00:48

so if we want to give this a value we

play00:50

can do we set it equal to something

play00:53

now we also have to kind of put the

play00:55

typing

play00:56

on the right hand side of this

play00:57

expression as well

play00:59

so this thing right here we also have to

play01:02

put

play01:02

on the right before we actually create

play01:05

the array

play01:06

and that might seem a little bit weird

play01:07

but this is just the way we work in

play01:09

go and then the array itself is

play01:12

curly braces not square brackets curly

play01:14

braces

play01:15

and then inside that i can add the items

play01:17

so 20

play01:18

25 and 30. so these are all ins

play01:22

and there's now three of these inside

play01:24

the array as

play01:26

we say right here now if i try to add in

play01:29

a fourth

play01:30

then it's not going to let me you see

play01:32

this error because we've gone out of the

play01:34

length

play01:34

of this declared length right here

play01:37

so an array unlike other programming

play01:40

languages you might be

play01:41

familiar with like python or javascript

play01:44

has to be

play01:44

fixed length we can't ever change the

play01:47

length of an array

play01:48

once it's been declared it has to have a

play01:51

specific

play01:51

length so we're going to move on to

play01:54

something called slices later which

play01:56

might feel a bit more like

play01:57

a raise as you're used to where you can

play01:59

change the length but for now just know

play02:01

that an array in go

play02:02

has a fixed length and it can't change

play02:05

all right so let me delete this

play02:07

if i try to add a type in here instead

play02:09

of an integer

play02:10

for example a string then it's not going

play02:12

to let me do that either all right so

play02:14

these all have to be

play02:16

integers because we said right here

play02:18

they're integers

play02:20

all right then so if we want to do a

play02:22

shorthand

play02:23

let me comment this out we can do and in

play02:26

fact i'm just going to copy this

play02:29

and then down here i'm going to say var

play02:31

ages is equal to

play02:33

and then just paste this in so this is

play02:35

the same

play02:36

as this so we don't have to type it on

play02:38

the left

play02:39

go just infers the type automatically

play02:41

for us okay but we still have to do this

play02:44

on the right hand side of this

play02:46

assignment

play02:47

all right then so let me down here print

play02:50

out the ages i'm going to say

play02:52

fmt dot print line

play02:55

and then inside there i'm going to print

play02:57

out the ages

play02:58

now we can also print out the length of

play03:01

an array and the way we do that is by

play03:02

using the built-in

play03:04

length method or len and then inside

play03:06

that we pass in

play03:07

the array we want the length of so we

play03:10

want the length of

play03:11

ages so if i save this and run the file

play03:16

then we should see the length and the

play03:18

array itself

play03:19

so there's the array and there's the

play03:21

length awesome

play03:22

let's do another example and this time

play03:25

i'm going to use the

play03:26

shorthand assignment so i'm going to say

play03:28

names is colon equal

play03:30

to and this time it's going to be square

play03:33

brackets

play03:35

and inside that i'll place a four to say

play03:38

there's gonna be four elements

play03:39

they're gonna be of type string and then

play03:41

inside the curly braces we'll do some

play03:43

names

play03:43

so yoshi and then mario

play03:47

and then peach and then

play03:51

bowser alright so there's our names

play03:54

array

play03:55

i'm going to do the same thing as we did

play03:57

for ages so

play03:58

let me duplicate this type in names

play04:01

and then names right here as well and

play04:04

then i'm going to run this file

play04:07

and we can see right here the ages and

play04:09

also now the names and the length of

play04:11

names awesome so that is arrays and

play04:14

remember

play04:15

the length is fixed so now i want to

play04:18

talk about

play04:19

slices and slices are more like

play04:22

typical arrays from other languages

play04:24

where we can't

play04:25

change the length we can add items to it

play04:28

or we can take items away from it

play04:30

so i'm going to say right here slices

play04:32

and by the way they use

play04:34

arrays under the hood all right so

play04:37

they still use the array type under the

play04:39

hood but we can manipulate a slice a bit

play04:41

more

play04:42

so what i'm going to do is create a new

play04:44

slice called scores

play04:46

and i'm going to set it equal to square

play04:48

brackets

play04:49

and then i'll say the type inside this

play04:51

slice and then i'm going to do

play04:53

curly braces and then i'll just place in

play04:55

some integers so

play04:56

150 and 60. and

play05:00

notice this time i've not placed a

play05:02

number inside the square brackets

play05:04

so when i don't do this it creates a

play05:07

slice for me

play05:08

not an array a fixed length so

play05:11

it's pretty much the same other than

play05:13

that we just don't put a number in here

play05:15

so what if i want to change the value of

play05:17

one of these things

play05:19

well i can do that and in fact let me go

play05:21

back to arrays because we can also

play05:22

change the values of arrays as well if i

play05:25

say for example

play05:26

names and then we want one that's

play05:29

position one and it starts at zero

play05:31

zero one if i wanna set that to be

play05:35

something else i can't i can set it

play05:36

equal to

play05:37

luigi that's going to change this to

play05:39

luigi i can also do that for slices

play05:41

so i can say scores and then position

play05:44

two so that's zero one

play05:46

two this one and i can set it equal to

play05:48

something else like 25

play05:51

all right now i can also now append

play05:54

items to this slice i can't do that to

play05:58

an array but i can to a slice

play06:00

so if i want to append something i say

play06:02

append

play06:04

and then in parentheses what

play06:07

slice i want to append to well that is

play06:09

the scores one

play06:10

and then what is the element i want to

play06:12

append to it well i'll add on

play06:14

an 85. now this

play06:17

function right here doesn't actually

play06:19

change

play06:20

this scores variable what it does is

play06:24

return

play06:24

a new slice for us so if we want to

play06:27

update this with the new slice we have

play06:29

to say

play06:30

scores is now equal to append

play06:33

scores85 does that make sense because

play06:36

automatically it doesn't append it it

play06:38

just returns a new slice

play06:39

and then that new slice is being

play06:41

assigned to scores so we're kind of

play06:43

overwriting

play06:44

this variable with a new slice so

play06:47

now let's try printing this out i'm

play06:49

going to say fmt dot

play06:51

print line and we're going to print

play06:53

scores

play06:55

and the length of scores

play06:58

so if i run this file now then we should

play07:01

see

play07:01

first of all that this element has

play07:03

changed

play07:04

from mario to luigi and we can see that

play07:08

right here

play07:08

so we get luigi instead of mario and

play07:10

then down here where we output the

play07:12

scores we have the extra value 85

play07:15

and the length which is now four not

play07:17

three as we first

play07:19

initialized it all right so

play07:22

that is slices and that is arrays

play07:24

there's one more thing i want to talk

play07:26

about

play07:26

and that is slice ranges

play07:30

so a range is a way to get a range of

play07:33

elements from an existing

play07:34

rayoff slice and store them in a new

play07:37

slice

play07:38

so what i'm going to do is say range 1

play07:40

is colon equal

play07:41

2 and remember we use colon equal when

play07:44

we're first

play07:44

initializing a variable we set that

play07:47

equal to

play07:48

names and then in square brackets i'm

play07:50

going to say go from position 1

play07:52

2 3. now what i'm going to do is just

play07:56

print this out fmt dot print line

play08:00

and i'm gonna output range one like so

play08:03

now if i come down here and i run this

play08:05

we're gonna see this range

play08:08

and it's luigi and peach so if we take a

play08:12

look at this remember we

play08:13

replaced position one with luigi which

play08:15

is why we get luigi

play08:16

so that's position one and that's where

play08:18

we're going from so it includes position

play08:21

one

play08:21

up to position three so one two

play08:25

three but it doesn't include position

play08:27

three

play08:28

so it just gets one including this two

play08:31

three but not including three so we end

play08:33

up with these two

play08:33

right here which is why we get them down

play08:35

here all right

play08:37

so it's inclusive of the first number

play08:39

but not of the second

play08:41

so let me do another range i'm going to

play08:43

say range

play08:44

2 colon equal to names

play08:48

and then this time i'm going to say go

play08:50

from position 2 colon

play08:52

and then just leave it at that and what

play08:54

that does is say okay we'll just go to

play08:56

the

play08:56

end of the array or the slice and get me

play08:59

everything

play08:59

up until the end so let me output this

play09:02

right here range

play09:03

two and see what happens save it and run

play09:06

it

play09:08

and we can see we get peach and bowser

play09:10

so

play09:11

from position two so zero one two

play09:14

up until the end including the end one

play09:16

that's what this does

play09:18

all right so let me say now range

play09:21

three is colon equal to names

play09:24

and then this time it's gonna be colon

play09:27

three so this but the opposite way

play09:29

around

play09:29

so this means go from the start and get

play09:31

me up to position three but not

play09:33

including position three

play09:34

so we'll say range three right here just

play09:38

to see if this works

play09:39

spell this correctly and save it

play09:43

so let's run the file and now we can see

play09:46

yoshi luigi and peach so from the very

play09:49

first position

play09:50

up to position three because we don't

play09:54

include the third one this is zero

play09:56

one two we don't include the third one

play09:58

all right

play09:59

cool so that is ranges in a nutshell and

play10:02

we can

play10:03

append these ranges as well because at

play10:05

the end of the day they're just

play10:06

slices so i could say range one is equal

play10:09

to

play10:10

append and then we're going to take

play10:12

range one

play10:14

and append cooper like so

play10:17

and then we can just print this out so

play10:20

i'm going to say

play10:20

fmt dot print line

play10:24

and then output range one

play10:27

like so run this again and we should see

play10:30

that

play10:30

range one now has cooper at the end of

play10:33

it all right

play10:34

so there we go my friends that is arrays

play10:37

the length of arrays cannot change and

play10:40

slices and the length of slices

play10:42

can change and we can get ranges from

play10:45

existing arrays and store them in new

play10:48

slices

play10:49

now most of the time you'll probably use

play10:51

a slice instead of an array

play10:53

but there might be times when you use

play10:55

these as well

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
Go ProgrammingArraysSlicesFixed LengthDynamic DataData StructuresProgramming TutorialCode BasicsGo LanguageArray Length
¿Necesitas un resumen en inglés?