Go (Golang) Tutorial #13 - Pass By Value

Net Ninja · Beginner ·🌐 Frontend Engineering ·5y ago

Key Takeaways

Explains pass by value in Golang and its implications for variable passing

Full Transcript

all right then gang so go is what's known as a pass by value language and this basically means that when we pass variables around as arguments in functions go makes a copy of those values for the function to use so we're going to dive into what that means for us as coders in this lesson so in go variable types can be split up into two distinct groups i'm just going to call these groups group a and group b for now but we'll give better names to them later on these are just the types that we've learned about so far plus an extra one called a struct which we're gonna learn about later on now there are other types which can go into these different groups but we've not covered those yet so i've left them out for now but understanding the difference between these two groups of types and how they work is pretty important and it's going to affect how you write go code so to demonstrate my point let's dive into a couple of examples first then we'll circle back around to the theory so i've got a name variable declared right here which is a string and remember that belongs to group a types strings ins bools floats arrays and structs so i have this string in this variable i've also created this function called update name and that takes in a string which we refer to as x and inside the function we take that string and we update the value of it to wedge so what if i call this function update name and i pass in the name variable which is t at the minute we take in that variable and we update the value of x that value to wedge inside the function then at the end down here we print out the name variable after we've run this function so what do you expect to see here do you expect to see tifa or wedge because we've updated the name inside this function you'd probably expect to see wedge but let's take a look and see what happens i'm going to open the console run the file go run main.go and we see tifa so it's not actually changed the value of the name inside this function so why not well what's happening is every time we pass a value or a variable into a function go creates a copy of the variable so this is a copy of the name variable not the original name variable and then inside here all we're doing is updating the copy of the variable and not the one we actually defined right here it creates a copy of that inside the function and that's the one we update which is why we still see tifa down here when we print it to the console so to understand this a bit more i want to talk about how variable values are stored on our computers in memory now our computer memory is a bit like a massive sequence of memory blocks where each block can store a single value now each block also has a unique memory address associated with it and our computer can use the memory address to either read values from or write values to that block now when we create a variable for example called age we store its value in one of these blocks and the variable name age acts as a label for this block and the memory address so that when we use a variable in our code our computer knows which block and which memory address is associated with and it can read the value inside that block now if we have another value or another variable its value is stored inside another block now when we pass one of these values into a function go copies that value and places it into another block whilst the function runs and this is the value that will be used inside that function now if we change that value inside the function it's this value we change not the original so when we print out the original variable after the function runs we still get its original value because it's not been changed only the copy has been changed so this is how passing around variables in go works a copy is created and stored in its own memory location so when passing variables in this group of types strings hints bools arrays floats and structs into a function as an argument changing the value of that argument inside the function does not change the original value it only changes the copy so one solution to this is to actually return a value here if we actually want to update this name so we could return x right here but we also have to specify the return type in the function at the top which is going to be a string so now what we could do is say well okay name is going to be updated to equal whatever this function returns to us in which case it's going to be wedge and if i save this now and run the file then we should see that it's updated to wedge right here awesome so that's the behavior of these types right here in group a now i want to move on to the other group of types group b so if we scroll down here a bit i've got commented out at the minute so let's just make it visible a menu which is a map and this remember is one of the group b types which is slices maps and functions so we have this map right here i'm also going to paste in a function at the top that i've created as well called update menu that takes in a map of exactly this type right here and we call that y inside the function and again we update y right here we say y this element is equal to 299 so the same as we did over here before before we returned a value we're just passing an item in the map and updating the map inside the function and then down here what i'm going to do is call that function update menu and pass in the menu and then i'm going to print out the menu so fmt dot print line menu so what do you think is going to happen here remember with this group of types right here it doesn't actually change the original value what's going to happen here is it going to change the original value or not well let's save it and find out so if we run the file then we can see right here the map and we can see now this coffee is 299. now it wasn't there in the original one so it's added in this element right here coffee is equal to 299. so which changed the original value of menu so what's going on here now the explanation i'm going to give you here is a simplistic version of what's happening under the hood so when we create a variable which is a type from group b go does two things first it stores the underlying data in memory in its own block and then it stores a value which contains other information including a pointer to the underlying data in another block and the variable name is associated with this memory block so in essence the value is split up into multiple memory locations the underlying data in one and a wrapper which contains a pointer to the underlying data in another now we'll learn more about pointers later but all they do is basically point to another memory location so when we use this variable in our code go find this block sees the pointer to the other memory block and reads from or writes to this underlying data so that when we pass this value as an argument into a function first go still does make a copy of the variable that bit doesn't change we always make a copy but it's copying the value stored inside this memory block where the pointer or the reference is stored not the underlying data that's not copied and now this copy contains the same pointer pointing to the same underlying data so when we change the variable inside the function go looks at the copied variable in memory it sees that it points to the other block then it updates the value in that block so it changes the original value so that's the difference between these two groups of data and how they work of these two groups of types if you like and how they work so to give these groups better names we'll call them pointer wrapper values and non-pointer values anyway now we know how these groups of types work i want to dive a little deeper and talk about pointers remember we said that pointers were the things that pointed to another memory block or memory location so we'll talk more about those next

Original Description

Go is a "pass by value" language -- we'll talk about what that means in this Go tutorial. 🐱‍👤 View this course in full without ads on Net Ninja Pro: https://netninja.dev/p/learn-go-golang 🐱‍💻 Course Files: + https://github.com/iamshaunjp/golang-tutorials 🐱‍👤 JOIN THE YOUTUBE NET NINJA GANG - https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join 🐱‍💻 🐱‍💻 My Udemy Courses: + Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript + Vue JS 3 & Firebase - https://www.thenetninja.co.uk/udemy/vue-and-firebase + D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase 🐱‍💻 Useful playlists: + Modern JavaScript - https://www.youtube.com/watch?v=iWOYAxlnaww&list=PL4cUxeGkcC9haFPT7J25Q9GRB_ZkFrQAc 🐱‍💻 Download Go - https://golang.org/dl/ 🐱‍💻 Go Numeric Types (bits) - https://golang.org/ref/spec#Numeric_types 🐱‍💻 Go Standard Library (bits) - https://golang.org/pkg/ 🐱‍💻 VS Code - https://code.visualstudio.com/ 🐱‍💻 Social Links: Facebook - https://www.facebook.com/thenetninjauk Twitter - https://twitter.com/thenetninjauk Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch →