Hang tight while we fetch the video data and transcripts. This only takes a moment.
Connecting to YouTube player…
Fetching transcript data…
We’ll display the transcript, summary, and all view options as soon as everything loads.
Next steps
Loading transcript tools…
Golang Tutorial for Beginners | Full Go Course | TechWorld with Nana | YouTubeToText
YouTube Transcript: Golang Tutorial for Beginners | Full Go Course
Skip watching entire videos - get the full transcript, search for keywords, and copy with one click.
Share:
Video Transcript
in this full course you are going to
learn about one of the youngest
programming languages that is becoming
more and more popular in the cloud
engineering world which is go or also
commonly known as go link you will learn
everything you need to get started with
go and start using it in your projects
we're going to write a very simple cli
application to learn the basics of go so
instead of learning the concepts and
syntax of go with isolated examples you
will learn them while building an actual
application throughout the tutorial
so first let's see a detailed overview
of what you will learn
before diving right into the syntax you
will first understand why go was even
developed its use cases and differences
to other programming languages
as a next step we will set up our local
development environment and see how the
basic structure of a go file looks like
then as we start writing our simple
ticket booking application you will
learn the core concepts and syntax like
the most common data types such as
strings integers booleans as well as
arrays slices maps and struts you will
also learn about variables and constants
about formatted output getting and
validating user inputs a concept of
pointers in go as well as variable
scopes then you will see how to control
the application flow with loops if else
and switch statements as well as how to
encapsulate logic
in functions and generally how to
organize your code in go packages
finally we will make use of go routines
to parallelize some of the execution to
make our application faster with
concurrency so we're gonna learn a lot
of things in this course and i hope you
are excited to get started also i want
to mention that all the demo code from
this course is available in a git
repository which we will link in the
video description so you can follow
along easily
we have put a lot of effort in creating
this course so if by the end of this
course you think it was valuable for you
let me know by leaving a like and
subscribe for more content like this
and also be sure to check out techworldwithnana.com
techworldwithnana.com
for online courses and a complete devops
educational program
if you want to further educate yourself
and bring your career to the next level
now for viewers absolutely new to
programming in general you can also
check out my python course on youtube
which is even more targeted to complete
beginners in programming and with that
let's get started go was created by
google in 2007
and open sourced in 2009 so it's a
pretty young language
now whenever you hear about a new
programming language the first question
you probably have is
why do we need yet another programming
language what is the purpose of it or
how is it better or different from other
already existing languages so before
diving into the syntax let's see what
was the motivation behind creating the
go language well the infrastructure
where the applications were deployed
changed a lot in the last few years
multi-core processors became common and
also using cloud infrastructure with
hundreds or thousands of servers with
multiple processors to deploy
applications became pretty universal so
infrastructure became much more scalable
dynamic and had more capacity however
most languages couldn't help in writing
applications that would take advantage
of these infrastructure improvements so
basically you had applications that
would just execute one task at a time in
order but with infrastructure
improvements it was possible to now
write applications that would execute
tasks in parallel do multiple things at
once this way making the application
faster and more user-friendly a simple
example is if you are using google drive
you may be uploading or downloading
files and folders but you can keep
navigating back and forth in the ui so
downloading uploading and navigating the
ui all happen in parallel or consider
youtube you can be listening to this
video then scroll down to the comments
write a comment yourself like the video
etc so the application allows you to do
multiple things at once without
affecting any other task and this is a
concept of multi-threading so each
thread is basically processing one task
and you can have many of them running in
parallel and this makes applications
fast but may also cause some issues for
example on google docs many users can
work on the same document at the same
time so when you have two users changing
and adding stuff at the same time to the
same document this should work smoothly
without one user overriding all the
changes that another user is making
another example where such issues may happen
happen
when things are processed in parallel is
a booking system for buying tickets or
booking a hotel etc let's say again two
users are trying to book the last
remaining ticket at the same time of
course this should work in a way that no
double booking happens and this concept
is called concurrency and needs to be
handled by developers in code so they
must write code
that prevents any conflicts between the
tasks when multiple tasks are running in
parallel and updating the same data and
many languages do have features for
implementing such applications however
the code can get pretty complex and
handling and preventing the concurrency
issues can be pretty hard and with
complexity of course there is always a
higher risk of human errors and that's
where the main purpose and difference of
go comes into the picture so go was
designed exactly for that purpose to
make writing multi-threaded concurrent
applications that take advantage of the
new performance infrastructure
much easier
and we will learn about this in more
detail at the end of the course when we
use go routines
so logically enough the main use case of
go or what it's best used for is writing applications
applications
that need to be very performant and will
run on the modern scaled and distributed
infrastructure with hundreds and
thousands of servers typically on a
for developing go they wanted to take
the simplicity of syntax of a more
high-level language like python and the
speed and efficiency
of a lower level language like c plus
plus so you will see the combination of
these things in go and i have to note
that go is used on the server side or
the back inside of the applications and
these types of applications can range
from microservices and web applications
to database services and so on in fact
many cloud technologies or technologies
that run on modern cloud environments
are actually written in go like docker
hashicorp vault kubernetes cockroachdb
and so on now on top of this main
purpose of go go actually has a lot of
other advantages one of them that i
already mentioned is it has a very
simple syntax which makes your code very
maintainable easy to read and extend
another advantage is that go
applications can be built very fast they
are also very fast in startup and also
when they're running plus go is very
resource efficient which means it uses
few resources or it requires fewer
resources like cpu and ram to run
go is also a compiled language and it
compiles actually very quickly into a
single binary and you can deploy it and
run it on different platforms in a
consistent way so no matter which
operating system or which environment
you're using you can take that same
binary and basically use it across
different platforms so considering all
these benefits of simplicity and speed
and so on go is becoming more and more
popular for writing
simple automation applications and
command line interface applications for
devops and sre tasks as well
so now that we know why go was created
and what differentiates it from other
languages let's jump right into learning
the core concepts and syntax of go
now to start writing a go project we're
gonna need two software programs first
of all we're gonna need go compiler and
second we're gonna need an ide or
integrated development environment where
we're gonna write
code for go and also execute it as an id
we're gonna use visual studio code which
is super easy to download and install so
if you don't have it yet on your
computer just type in install visual
studio code in google and basically on
their official page you have the
download options for
all operating systems so go ahead
download and install it so that's the
first part
i already have visual studio code
locally so i'm gonna skip this part and
second we're gonna need to install go
compiler right now i don't have go
locally that's why when i type go it
tells me command not found so we're
gonna install go which is also super
easy again type install go
and on their official page you have
download and install guide and again for
different operating systems i'm working
on mac so i'm gonna download the go
package for mac awesome once that's
downloaded just click on the package
and it will show you an installer which
basically lets you install go step by
step setting up everything necessary in
the background so we're gonna do continue
continue
install for all users we're going to
leave all the defaults install
install authorize
authorize
and as you see installation was successful
successful so
so
so if i close this window we can remove
the installer and go back to the
terminal and type go as you see we have
go installed that's why you see a bunch
of go commands that you can start using now
now
great so we have everything prepared
let's create a folder in which we're
and i'm gonna call it booking
booking app
and using visual studio code we're going
to write go program in that folder so
and i'm in the booking app folder you
can also simply just open
visual studio code and then basically
that you want to work in and you have
the same result and i'm going to make it
a little bigger
for convenience and there is one more
thing that we need to do to prepare our
setup and that is installing a go
extension inside the visual studio code
the extension will basically help us in
writing the go code it will give us a
nice syntax highlighting intellisense to
basically easily navigate our code help
with troubleshooting and so on so
extensions for different languages make
it much easier to write code in that
language so let's go ahead and do that
to complete our setup and on the left
side right here you have the extensions tab
tab
so if i click inside and then search go
go
it will give us all the available
extensions for visual studio code and
the first one with the most downloads is
the official one from go team at google and
and
you also have a description of what that
extension gives you and that's the
extension we're going to use so
click on install
and that's it now we're all set up to
start writing our first go application
and for that obviously we need to create
a file and this is going to be the main
dot go file with dot go extension you
will see a bunch of pop-ups here to
install things for the go extension so
go ahead and click on install all and
that will install and set up the rest of
the stuff
and main dot go is basically a standard
name for the main file where the go
application code is written
and to see that in the file explorer we
have this booking app folder and inside
we have this main.go file
now how do we start writing code in go
like printing a simple
hello world message to the console
quotes hello world
and we already see the first
benefit of a go extension because it
tells us that this code doesn't work
and as you see the error says that go
can't find a file called go.mod
so the first thing we need to fix is to
make our go application into a project
and for that we need to basically
initialize it
that's the error that we get here and to
do that we're going to open a terminal
in visual studio code
new terminal window and
this will give us
terminal in booking app folder which
we're in
which is very convenient and here i'm
gonna run a go command called go
mod or module init
init
and basically name of the project we
called it booking app so let's use that
name so this is gonna basically initiate
our go application into a module or a project
project
and we're calling it booking app so
let's execute
and save
so what this command actually did in the
background is it generated this go dot
mod file which simply describes the
project with the name
of the project and the version of go
that is used here
so the first issue is now fixed now we
have another error that says expected package
package
so in go everything is organized into
packages and we're going to be using go
packages throughout our application and
when we create our own application we
also have to include it in a package and
doing that is actually very simple
as the first line of our go application we
we
define keyword package
and then name of the package which our
application will be part of and the
standard name for the main application is
is
package main so now we have an
initialized go application which is in a
package called main moving on to the
next error we now see again a different
message that says that a declaration is
expected now i have to note here that
you may actually have a different
sequence of errors so you might see a
different message here but i'm going to
show it to you with my examples so in
this case we have a missing declaration
and that is basically
goes way of saying
i don't know where to start executing this
this application
application
so give me an entry point
and we have to declare
the entry point of our application
because when we run go applications we
need the main starting point for the
execution so go needs to know where does
it start executing the code on which
line because if you have multiple files
in the go project you need to give go
compiler a starting point the first line
of code where the execution starts and
the entry point is
a main function that go will look for
whenever you execute your go application
and we create a main function using func keyword
keyword
name of the function again it has to be
called main
and we have to put
our logic
whatever we are executing within that
main function so now go will know where
to start executing our application and
for one go application you're going to
have a one main because you can only
have one entry point
to your application so now we have a
slightly changed syntax highlighting for
our print function and if we hover over
it we see another error message that
says undeclared name now we've come to
the point where our application belongs
to a package we have the entry point so
go knows where to start the execution
and it sees that print is the first code
that it's going to execute but the
problem here is that it doesn't know
where print is coming from that's why we
see undeclared name and print is a
function that comes from a go package a
built-in package called
fmt or format and we have to explicitly
import any packages from which we're
using the functionality so we're going
to do import
quotes fmt that's the name of the go package
package
and to use a print function or any
function from the package
we're going to do
fmt dot print
and immediately
as you see
the error is gone
and as i mentioned similar to many other
programming languages everything is
organized into packages so the go
program that we installed actually
already has some built-in packages with
a bunch of functionality
that we can use and one of them is this
package that we just imported and as i
said the packages have functions that we
can use so whenever we want to use a
built-in go function to print a text to
get user input to validate something etc
we need to
explicitly import it from one of the packages
packages
so think of the packages as containers
of various functionalities that go gives
you readily available for you to use
when writing your applications now how
do you know which functions
are in which packages or let's say if
you need to get a user input how do you
know in which package you have that
functionality available well you
actually have to look up the
documentation to see that or basically
just simply google to find the right
package and of course with time when
using go and its packages you are going
to know the most commonly used packages
and all their functionalities and a cool
thing we have here is you see this
underline under the fmt package
and if i hover
over it you see a link that actually
takes you to the official documentation
of the fmt package so here you can
actually see what functions you have
available in that package and so on
so with this we have our first fully
functioning go application that we can
now execute
so let's clean up our terminal and
executing a go application is very easy
we have go command for it called go run
and name of the file that we are
executing which is main dot go so go run
will basically
execute this file
it will
look for the main function and execute
the contents or lines within that
function one by one we just have one
line so that's getting executed and
we're seeing hello world in the output
we can do final optimization here
to add a new line at the end of this
print statement and to do that we're
simply going to use a different function from
from
format package called print ln
so this will print whatever we pass here
with a new line and let's execute that again
again
and there you go
now that we have the minimum program
structure and know how to run go
programs let's start writing our booking
application logic the very first thing
we need to do in our booking application
is to greet
our users when they visit the application
application
so let's write some welcome message and
information about the conference for
which they are booking the tickets
so instead of hello world
we're gonna write welcome message like welcome
welcome to
to
our conference booking
booking application
application
and we can write another message
like get your tickets
tickets
here to attend and again if we execute this
this
we're gonna see our welcome message
now let's say our conference has a name
and we're using this name in many places
in our application in the welcome
message in the thank you message when
the user books the ticket on the ticket
itself etc and whenever we have a value
like conference name
that is used in many places throughout
the application
it's the most common usage for variables
every programming language has a concept
of variables where instead of repeating
this value everywhere you store it once
in a variable assign it a name and now
you can reference that value using its
variable name wherever you need it in
your code now if the value changes you
don't have to find and update it in
multiple places throughout the
application code but you can simply
change it in one place where you
assigned it to a variable and that's it
so how do we create and use variables in go
go
well we have
the value
like the name of the conference let's
call it go conference
and we store that value
in a variable and we can give that
variable whatever name we want like this
let's call it a name
and finally we tell go
that we are creating a variable using a
var keyword
so this basically lets us store the
value go conference the conference name
in a variable called name so
now we can use that value by referencing
the variable name wherever we need it
now with variables it's a good practice
to create variable names that properly
describe what the value is in our case name
name
baby two generic so to make it more
specific and clear we can call it a
conference name
and note the camel case syntax here
which is a pretty common variable naming
convention in different programming
languages including go
and if i save those changes you see that
we get a red line
under our variable definition and that is
is
something specific to go language so in
go unlike many other programming languages
languages
when we define a variable or when we
create a variable with a certain value
and we don't use it in the code
we get this error that actually says
conference name declared but not used
so to fix this error we actually have to
use that variable and note that same
error applies when you import a package
but you don't use that package in your
code you get the same error that package
gets imported but not used which is a
very good reminder to clean up your code so
so
to fix this issue we're simply gonna
print out that variable value using
and again when i save this change the
error disappears
so let's clean up the terminal output
and run our
go application again
and there you go you see go conference
printed out now let's actually use that
conference name in our welcome message
instead of generic our conference we're
going to reference whatever we define as
a conference name for that
first of all let's delete the print
statement and again as a common practice
we're going to define the variable at
the beginning of the function and we can
use the variable within the print
message by dividing the actual text
that we have here
and the variable name
with commas inside the print alien function
so this will be substituted by conference
conference name
name
actual text and the variable name will
be separated by commas
and let's save this and if i execute our
go application again
we will see welcome to goconference
booking application so it took the value
from here
also note that the space automatically
gets added before and after the variable
value now what we also need in our
application is the tickets for our
conference and let's say we have total
of 50 conference tickets available for
users to book and for that we will also
create a reference called conference
tickets to store that value once and
then we can reference it as many times
as we want so let's call it conference tickets
tickets
and the value will be 50. we have 50
tickets available now
this value actually does not change
throughout the application right we have
50 conference tickets and it will always
stay 50. while our application
is running and for such values that do
not change or stay constant instead of
variables we have constants
constants
now as you might think the conference
name could also be constant because it
also doesn't change throughout the
program but for this example we will
leave it as a variable so instead of var
keyword here we're going to use const
and that will give us the same type of
reference as with variables but this
time we cannot change the value of this
constant but we can use it and reference
it in our application exactly the same
way as our variables
so the const keyword tells go that this
value is not allowed to change and if we
and
somewhere in the application code change
it to some other value and then try to
like this
we get a warning here right away that
says cannot assign to conference tickets
because it's declared as a constant
but if we change it to var
and save you see that the warning disappears
disappears
so let's change it back to const and
and
clean those lines up
now when users start booking the tickets
obviously we need to keep track of the
ticket count so when 50 users book their
tickets we inform the rest that the
conference is completely sold out so
every time someone books a ticket we
need to basically reduce the number of
available tickets that users can book
and for tracking that amount we're going
to create another variable for remaining tickets
and we're going to call it remaining tickets
tickets
which again is a variable because as
users book their tickets this value will
get less and less and it starts at 50
because that's how many tickets we have
in total and again we have this warning
because we're not using it so let's
actually use that in our welcome message
to inform the users about how many
tickets are available for the conference
and how many of them are still remaining
so between these two lines i'm going to
add another print statement
and here we're going to say
we have
total of
this many are
and if i save this the warning will go
away because we are using
using
both of these values
values
in our code
so again separating the actual text from
the variable reference using commas
now let's run our updated application and
and
in the message we have the name of the
conference and here it says we have
total of 50 tickets and 50 are still available
now whenever we're printing our text
mixed with variables we can use a
function called printf from the format
package this function is specifically
used for printing formatted data
so it tells go how to format the values
of the variables and generally it makes
writing these kind of outputs
easier so with printf
this line for example will look like this
this
so instead of print ln we're going to
use printf
another function from the format package
and instead of the conference name
reference we're going to use what's
called a placeholder and annotate that
using percentage sign and v
and you see the syntax highlighting here
that shows that it's a special character
for placeholder but of course we still
need to reference whatever
variable we want to substitute here
right and we do that right here with a comma
comma
and then conference name
we have the same output one thing that
is different here is the new line is
missing because we were using println
that automatically added a new line in
this case we're gonna add it explicitly
using backslash
n so that's a character for newline and
if i save this and run we have exactly
the same output as before now let's do
the same for the second print statement
first change it to printf take this
reference here and substitute it with
percentage v do the same for
the second
variable reference
and again we need to
replace so basically we need to tell go which
which
variable values should be used to replace
replace
those placeholders and of course they
should be in a correct order when we
have multiple such placeholders so the
first one is
conference tickets
the second one is remaining tickets
backslash n
save it and there you go
now as i mentioned printf
or print format function allows you to
tell go how to format the variables
that you are referencing here the
percentage v is the default format but
you have other specific formats also available
available
if you want the values to be displayed
differently and you can see this whole list
list
in the gold documentation
under the fmt package link
so the percentage v is the one we used
we have a lot of other options as well
now sometimes when we create a variable
we don't immediately know its value for
example when we're getting user input
like a user entering their name and
and
date of birth etc in the application we
don't know that value before because we
don't know what the user is going to enter
enter
so we create a variable
and later we assign it the value which
is possible to do in go just like in
other programming languages so let's see
the syntax for that
so here let's say we define a variable
called username
and we don't know what the value of that
variable is going to be
for their name and this is a syntax for
comment so whatever starts with
double forward slash signs is basically
interpreted as a comment so it's not
executed as code so let's say we have
some imaginary code here that asks for
user input and
and they
they
and that user name that we get is
and finally we can actually use that value
value
so we have defined a variable here and
then we are assigning a value for that variable
variable later
later
on a separate line however when i save
this code you see that we get another
warning here that says
unexpected newline expecting type so
what's the problem here
and why is it expecting a type well in go
go
all values have data types and generally
in any programming language you have
multiple data types for different use
cases and go isn't an exception
the difference between these languages
is however which data types exactly they
support so each language has its own set
of data types
two most basic and common data types are
strings and integers for textual data
like the welcome message
the name of the conference so anything
between the quotes basically
is a string data type for numeric data
like ticket count
h and so on we have integer
data type and again you see the syntax
highlighting for the integers and
strings are different because go
basically knows this is a string this is
an integer
so these are the two most basic ones but
we're going to learn a few other data
types as we go along
here however it's important to
understand that each data type can be
used differently and behaves differently
for example you can do calculations with
integers but you can't do calculations
with strings
you can chain or get a subset of a
string but you can do that with integers
so the main purpose of having types for
values in code is to avoid accidentally
using an integer as a string or vice
versa and use one data type instead of
the other which may break your application
application
so when we create variables in go it
needs a type now you may be thinking
when we created these two
two
variables right here
these two variables and a constant we
didn't specify a type so why didn't we
get the same syntax error here well when
we create a variable
or constant and assign a value to it
immediately on the same line
go can imply
the data type based on the value
so go knows that this is a variable type
for string and this is a constant and
variable types for
integers because of the values but when
we do not assign a value immediately go
doesn't know what type of value you are
going to store here so it asks you to
explicitly define a type to make your
code basically more robust and prevent
prevent
you or other developers from
accidentally assigning a wrong data type
value to that variable later in the code
so in this case we need to define a type
explicitly how do we define a type super
easy at the end we just say this is a
variable of string type if i save this
the error disappears and again you see
the syntax highlighting for the type
and the same way we can define a
variable for
integer type let's say
user tickets
which is a number of tickets user wants
to buy and this is going to be an
integer type
and somewhere here
we're going to ask user for the input
and let's say they enter
2 and in the print statement with printf
we're going to say
user whatever their username booked
booked
this many
and reference
the respective variables and again
let's run this
and here we have our output
now you probably already noticed
something really cool about go
especially if you have worked with other
programming languages before and that is
that while we're writing this code
if we make some mistakes if we have
errors in our code for example defining
a variable and not using it or
forgetting to specify a type etc go
basically detects those errors before we
even run the application so by the time
we're ready to execute the application
we have fixed a bunch of errors
that go
identified and
highlighted for us in many programming
languages that's not the case usually
you discover these kind of errors when
you run the application not while you're
coding and that is a big advantage of go
now going back to the types i mentioned
that go actually implies the types of
these three values automatically and if
we wanted we could actually print out
the types of variables
variables
using the printf function so with fmt printf
let's print out the types of these two
variables and a constant so conference
whatever type it has
tickets is
whatever type this one has
percentage t percentage t is a placeholder
placeholder for
for
the type of the variable that we're
referencing here not the value like
percentage v but the type so let's pass
in those references
references
and save
and if we run our application
we should see
the output here conference tickets is
int or integer
remaining tickets is in conference name
is string
so this lets you print type of any
variable now if we wanted we could
actually define the types explicitly
here even though it's not required so we
could do
conference name as a string
and int
and int
however specifying a type explicitly
when go can detect it
makes sense when want to specify a
different type than what go would detect
for example in go specifically again we
have multiple times for
numeric values so in addition to int or
integer type which represents whole numbers
numbers
we have int 8 in 16 and 32
and int
64 which corresponds to the length of
the integer so basically how big or how
large the number is
and in addition to that we also have
uiint or unsigned integer
which represents whole numbers like
integer but only positive ones so 0 and plus
plus
and here's a chart of all the different
numeric data types in go and obviously
each one has its own purpose
so the question is when to use which one
and why do we have so many different
integer data types for example well this
allows you to define data types in a way
that the values will automatically be
validated so if you're using uiint and
assign a negative value to it you will
get an error like in our case the number
of remaining tickets should never be
negative but with int type it can be so
somewhere in the code we can actually
set it to a negative number like this
but if we specify a type uint explicitly
instead and save it you see that it will
not accept the negative value so setting
a type may actually protect our variable
from getting a value that it's not
supposed to get and obviously you as a
developer are not going to assign your
variables a wrong value but if you're
doing some calculations on your
variables or some processing the result
of that calculation may be a wrong value
we also have float number type which are
for numbers with fractional parts so not
whole numbers this could be statistical
data like a conference attendance
compared to last year for example this
could also be monetary values like
prices of products in an online shop or
transactions in an online banking
application and so on so basically when
a number needs a higher precision float
number type needs to be used
but as i said there are other data types
in go besides textual and numeric types
which we will learn as well now there is
one more thing in terms of variable
definition in go and that is again
specific to go
is that we have an alternative syntax
for creating a variable and assigning it
a value directly this is like a
syntactic sugar of go language so
instead of this syntax for creating a
variable we can get rid of the var keyword
keyword
as well as the type and
right here before the equal sign just
add a column
and this will do the same as
before create a variable and assign it a
value now note here that with this
alternative syntax you cannot declare
constants so we cannot do
this with constants
it only applies to variables and it also
doesn't work if you want to explicitly
define a type for your variable like
now let's clean up our code and let's go
back to
our ticket booking logic
so this is a booking application so want
to allow users to book their tickets and
for that we want to ask users for their
personal information first like first
name last name etc and all these values
will be then saved into variables
like this
so we need some logic here that allows
the application to ask for user input in
order to read user input we use another
function from the same format package
so basically the format package
gives us different functions
to print out like this
formatted output
or read formatted input so it's used for
input output processing functionality so
let's scan the user input for their
first name because instead of assigning
the value directly as we did here we
want to get that value from the user and
then assign it to
the username variable now print function
like printf or println takes a message
as a parameter like this one a formatted
message and prints it
scan also takes a parameter which is the
input it needs to scan and the parameter for
for
scan function is the user input
but we don't know what the user will
enter as their name so we need a way to
save the user input
as a variable
and then
reference that value using that variable
name instead of directly assigning it here
here
and let's save it so this is supposed to
scan user input
and whatever user enters basically
assign that value to username variable
as a value now if we run this
application let's run it you see that it
runs it executes all those lines and
and
it just exits it doesn't wait for any
user input so we were not able to enter
anything and the value of the user here
or username variable is also empty so
there is one thing that we need to fix
here so before the username variable we
need to add what's called a pointer
like this so what is a pointer simply explained
explained
i said that we save a value in a
variable in order to use it later so
when we create a variable where does
that value actually get stored well
values are saved in memory on your
computer so that 50 or go conference
values are actually stored in memory but
whenever we reference that value using
the variable name we defined go compiler
must go and find that value in memory so
it needs to know where in memory exactly
it is stored or in other words it needs
to know the memory address of that value
and a pointer is a variable that points
to the memory address of another
variable that references the actual
value 50 for example and pointers in
golang are also called special variables
so to see that in the code let's
actually comment this out
and if we print out
any variable like remaining tickets for example
example
with value 50 this will give us
the pointer
this will actually print out
the memory location of the remaining
tickets variable let's actually see that
right here we have
value 50 and the next line is
a hash which is a memory address for the
remaining tickets variable so that's
basically a pointer
and it's also important to mention that
pointers is a concept used in the c
programming language but many popular
programming languages like java or
javascript for example to not have
pointers at least not exposed to you as
a developer so you will not see the
concept of pointers in many other
languages so again going back to our
scan function instead of passing the
value of
the username variable which is empty
we're passing the memory address of that
variable so that scan function
will read whatever the user enters and
assign that value
to that username variable in memory so
if i execute the application now
you see that it doesn't just exit it
actually stops at this line after get
your tickets here to attend and it's now
waiting for me as a user to input some
data and as a username i can input my
own name and if i enter it goes to the
next line and it prints out whatever is
in the username booked to tickets so now
we have that value whatever user entered
available in our code through this
username variable now to make this a
little bit user-friendlier we can also
ask the user explicitly what we are
enter
like this
and let's run again
and there you go so now we are actually
and then printing the result out
so that's one value
now let's read
other user data like last name email and
number of tickets user wants to book and
let's first call this
first name
let's create last name
which is also string
and email which is also string
and user tickets which we already have
which is an int
and now one by one let's actually scan
all those values
i'm going to copy these two lines
and we're going to say enter your last name
name
and we're going to save that
value that user enters in a last name variable
variable
again let's copy
copy
and the value will be stored in email variable
variable
and finally instead of assigning user
tickets directly we're going to ask the
user how many tickets they want enter
enter
number of tickets
tickets
and again this will be stored in user
tickets variable
and at the end let's actually print out
some kind of a thank you message
to the user
so let's write
thank you
first name last name of the user
you will receive
receive
a confirmation
email at whatever email address they
gave us
and don't forget the new line at the end
and now let's actually substitute those
placeholders with the actual
variable references so we have first name
name
last name and here we have
the third one
user tickets
and finally the email address they gave us
us
awesome so let's
clean this up and run our program
nana
enter your last name
my last name
email address
something like this
and finally number of tickets let's say
three tickets and if i enter this is the last
last skin
skin
so now it's gonna
execute the print statement that says
thank you
nashia for booking three tickets you
will receive a confirmation email at
now we're getting
user input but no tickets are being
booked the remaining tickets doesn't get
reduced it always stays 50.
so let's write some simple logic to book
the ticket which in our case will be
just reducing the number of remaining tickets
tickets
so after getting user info we will
simply add
remaining tickets
minus user tickets
so this will give us some value
50 minus how many tickets user booked
and then we have to save it back into
the remaining tickets variable to update
it right because we have to update the
value of this variable by assigning it
back now
when i save it we see an issue and that is
is
type mismatch
of uiint and int because we're doing a calculation
calculation
on two numbers which have different
types one of them
is you integer
and another one user tickets is an
integer so as you see in goal when you
do calculations between numbers they
have to have the same type one way to
handle this issue in many languages is
to convert
one of them to the other type
using various built-in functions that
you have available in the language
a simple solution for us
is to make the user tickets also you in type
type
because users can only book
positive number of tickets right they
can't book minus one or minus two number
of tickets so
let's make it you int as well and now
the error is gone
so that's our super simple booking logic
and after the thank you message we're
also going to print information about
how many tickets
are now remaining so let's say this many tickets
tickets remaining
remaining for
for
name
so with these changes let's now run our
go application
and again enter
enter
the user values
and let's say we're
buying 15 tickets
and enter
and as you see the remaining tickets are
now 35 50 minus 15 that we entered
before moving on i want to give a shout
out to castin who made this video possible
possible
kessen's k10 is the data management
platform for kubernetes
k10 basically takes off most of the load
of doing backup and restore in
kubernetes from the cluster
administrators it has a very simple ui
so it's super easy to work with and has
an intelligent logic which does all the
heavy lifting for you and with my link
you can download k10 for free and get 10
nodes free forever to do your kubernetes
backups so make sure to check out the
link in the video description and now
now we're saving user data in variables
and are booking the ticket for them
but when multiple users book the tickets
we need to save all these user data in
some kind of a list right to keep track
of who is attending the event and who
booked the tickets and for that we have
data types called arrays and slices
arrays and slices are commonly used data
types in go applications so let's create
an array for all the bookings so right
here i'm going to create a variable
called bookings and this is going to be
an array when we define an
array the first thing
we need is the size because arrays in go
have fixed size and for that we use
square brackets and within those square
brackets we define the length or size of
an array
and let's say we expect maximum 50 bookings
bookings
so we're gonna
say 50. so the size of an array is
basically how many elements can this
array hold so as i said array is like a
list of bookings or list of elements and
with the size 50 we're saying this can
have 50 elements in that list the next
thing we need to define is the type
of the elements
this array will contain a data type so
what kind of values are we going to
store in that is it going to be a list
of integers a list of strings etc in our
case let's say
we want to store a list of
names of the users who book the tickets
a name is a string so our array is going
to be an array of strings so that's the
data type
and finally
we need the actual value
right so this is the same syntax as
this one right here where we are assigning
assigning
a value directly to the variable so we
need to actually assign a value of an
array and we can have an empty array
like this
or we can
already put some elements in the array
and let's say these are some of the
and this gives us a bookings array with
size 50 with three elements already in
that array
now there are two things i want to
mention here first of all because we
have to define the type of the elements
for the array we can't
mix any other type here so we cannot
have names and then
an integer for example right this will not work and again this is specific to
not work and again this is specific to go you can actually mix the types in
go you can actually mix the types in some other programming languages the
some other programming languages the second thing i want to mention is that
second thing i want to mention is that even though we are starting with three
even though we are starting with three elements here we can actually update our
elements here we can actually update our array and add new elements up to 50 as
array and add new elements up to 50 as well as remove the elements so again
well as remove the elements so again this is a variable so we can add new
this is a variable so we can add new elements to the list and remove that
elements to the list and remove that during the application execution
during the application execution and usually
and usually when you create an array you actually
when you create an array you actually start with an empty list
start with an empty list like this because you don't know the
like this because you don't know the values at this point and as the program
values at this point and as the program executes you basically add new values
executes you basically add new values one by one so that's going to be our
one by one so that's going to be our starting point and because we are
starting point and because we are creating an empty array an alternative
creating an empty array an alternative syntax for
syntax for this will actually be to define the
this will actually be to define the array variable
array variable like this without assigning a value
like this without assigning a value and going with the default empty array
and going with the default empty array but as you learned in this case we have
but as you learned in this case we have to define the type
to define the type for the array because go doesn't know
for the array because go doesn't know the type and again you see here it's
the type and again you see here it's expecting type so what is
expecting type so what is an array type in go
an array type in go well it's actually
well it's actually a combination of the size that we
a combination of the size that we defined which is 50 and the type of the
defined which is 50 and the type of the elements
elements it's going to contain
it's going to contain like this
like this so
so this is actually
this is actually an array type and we're getting this
an array type and we're getting this error because we're declaring a variable
error because we're declaring a variable but not using it so let's actually use
but not using it so let's actually use it and let's start by adding new
it and let's start by adding new elements to that array how can we do
elements to that array how can we do that pretty simple actually we have
that pretty simple actually we have a syntax
a syntax with indexes so bookings array
with indexes so bookings array with index which is the position in
with index which is the position in which we're adding a new value like this
which we're adding a new value like this so again our array has
so again our array has 50
50 empty positions where we can add values
empty positions where we can add values and we're saying
and we're saying the position
the position 0 which is the first position let's
0 which is the first position let's assign this value and we can say
assign this value and we can say position
position let's say 10 let's assign
a different value but of course normally you would go one by one you would add
you would go one by one you would add the next value in the list like this
the next value in the list like this now in our case again we want to add a
now in our case again we want to add a name of the user
name of the user that booked the ticket we want to save
that booked the ticket we want to save the first name and the last name of the
the first name and the last name of the user so instead of assigning a value
user so instead of assigning a value directly we're going to say first name
add some space in between
in between and the last name
and the last name so this will give us first name last
so this will give us first name last name with space separated however as you
name with space separated however as you see here we get an error that first name
see here we get an error that first name and last name are not defined because
and last name are not defined because we're using these variables before they
we're using these variables before they are declared here again in a language
are declared here again in a language like javascript for example the order
like javascript for example the order doesn't matter so this would work in
doesn't matter so this would work in javascript but in go you have to use the
javascript but in go you have to use the variable after it has been defined in
variable after it has been defined in the code so we're gonna take this
the code so we're gonna take this assignment
assignment and basically move it
and basically move it down here
down here under
under the logic for
the logic for updating the remaining tickets
updating the remaining tickets and if i save this the error is gone so
and if i save this the error is gone so to wrap this up we're creating an array
to wrap this up we're creating an array variable
variable at the beginning which is defined as an
at the beginning which is defined as an array of strings
array of strings with 50 elements maximum
with 50 elements maximum and right here after user has entered
and right here after user has entered their first name last name and booked
their first name last name and booked the ticket we are adding that user's
the ticket we are adding that user's full name to the bookings variable and
full name to the bookings variable and to also see what's inside the bookings
to also see what's inside the bookings let's actually print out the contents of
let's actually print out the contents of the array and also some information
the array and also some information about the array to see how it actually
about the array to see how it actually looks like so let's do
looks like so let's do fmt print f
fmt print f and first let's print out the whole
and first let's print out the whole array
placeholder v and newline
and newline and this is going to be whole bookings
and this is going to be whole bookings array
array then let's print the first value
which is bookings at index 0
at index 0 and we need to use capital p here
and we need to use capital p here like this
like this then let's also print the type
then let's also print the type of the array
of the array like this
like this and finally let's print the size or
and finally let's print the size or length of the array and to get the size
length of the array and to get the size of an array we have a built-in function
of an array we have a built-in function called length
called length with l e n
with l e n that takes the array as a input so to
that takes the array as a input so to say
say and gives us the size of
and gives us the size of the array
the array and here we need percentage and capital
and here we need percentage and capital t
t and now let's actually run our
and now let's actually run our application and see how arrays work
book five tickets and here you see
and here you see all the array information so first of
all the array information so first of all we have the whole array that has
all we have the whole array that has one element
one element which is first name last name of my user
which is first name last name of my user and you see that it has square brackets
and you see that it has square brackets at the beginning and here at the end so
at the beginning and here at the end so basically this represents the
basically this represents the space for all the other elements in the
space for all the other elements in the array because we have a fixed size of 50
array because we have a fixed size of 50 elements and that's why you have a space
elements and that's why you have a space here
here then we have just the first value
then we have just the first value which is this one right here without the
which is this one right here without the brackets the array type is what we
brackets the array type is what we actually defined here
actually defined here as a type and then we have array length
as a type and then we have array length which is 50.
which is 50. now what happens if we try to add value
now what happens if we try to add value to this array
to this array at an index
at an index 52 for example so basically
52 for example so basically index outside the range of
index outside the range of the array size let's try to do that so
the array size let's try to do that so instead of zero index
instead of zero index we're going to do 52. again without
we're going to do 52. again without running the application
running the application go actually detected that your
go actually detected that your index is out of range or out of bounds
index is out of range or out of bounds and you need to fix that again if you
and you need to fix that again if you have
have some calculated number here
some calculated number here that you don't know refers to
that you don't know refers to a wrong index
a wrong index go will help you basically
go will help you basically detect that error immediately before
detect that error immediately before even running the application
now we have one issue with our array because what if you don't know the size
because what if you don't know the size of the array when you're creating it
of the array when you're creating it let's say we have an array for users who
let's say we have an array for users who sign up for our newsletter we don't know
sign up for our newsletter we don't know how many users are going to sign up
how many users are going to sign up right this could be anything between
right this could be anything between zero and indefinite so how can we fixate
zero and indefinite so how can we fixate the size here it could be same in our
the size here it could be same in our case because maybe not all 50 tickets
case because maybe not all 50 tickets get booked or maybe one user basically
get booked or maybe one user basically books all 50 tickets so we have just one
books all 50 tickets so we have just one booking and an array of
booking and an array of size 50 with just one value inside so
size 50 with just one value inside so how can we
how can we define a list that is more dynamic in
define a list that is more dynamic in size
size for such use cases
for such use cases so basically at least where we don't
so basically at least where we don't have to specify
have to specify a size at the beginning but it
a size at the beginning but it automatically expands as new elements
automatically expands as new elements get added to it
get added to it well exactly for that
well exactly for that use case
use case instead of array we have what's called a
instead of array we have what's called a slice
slice slice is basically an abstraction of an
slice is basically an abstraction of an array so it uses the array type under
array so it uses the array type under the hood but has a dynamic size and
the hood but has a dynamic size and working with slices is also more
working with slices is also more efficient than with arrays so generally
efficient than with arrays so generally using slices is actually a better option
using slices is actually a better option than
than using arrays in our application we will
using arrays in our application we will also use slice instead of an array
also use slice instead of an array and to define a slice we basically
and to define a slice we basically create an array without
create an array without a size definition
a size definition like this now in an array we added
like this now in an array we added new elements
new elements using this index
using this index which is not very convenient because for
which is not very convenient because for each
each new user we have to know exactly what is
new user we have to know exactly what is the next index
the next index that has a free
that has a free spot or free place for the next value
spot or free place for the next value in slices however we don't need to use
in slices however we don't need to use the index instead we can just say
the index instead we can just say add the next element to the slice
add the next element to the slice so the syntax for that is append
so the syntax for that is append again a built-in function from go just
again a built-in function from go just like this length function
like this length function and this append takes bookings
and this append takes bookings which is our slice
which is our slice and then whatever value we want to add
and then whatever value we want to add to this slice is a next element whatever
to this slice is a next element whatever index that may be
index that may be and then we have to assign this back to
and then we have to assign this back to our slice
our slice and as i said this is much nicer because
and as i said this is much nicer because we don't have to keep track of the
we don't have to keep track of the indices and let's remove this
indices and let's remove this and now we are working with dynamic
and now we are working with dynamic lists using
lists using slice
slice so adding a value to a slice is
so adding a value to a slice is different than to an array but
different than to an array but retrieving a value getting a value from
retrieving a value getting a value from the slice is the same so we can actually
the slice is the same so we can actually leave this syntax like this we can
leave this syntax like this we can change the wording here from array to
change the wording here from array to slice
slice and now let's
and as you see the slice basically has these brackets
these brackets directly wrapped around
directly wrapped around the value it has and the length of a
the value it has and the length of a slice is one so as we add new elements
slice is one so as we add new elements it automatically expands
it automatically expands and finally just as a reminder
and finally just as a reminder note the alternative syntax for creating
note the alternative syntax for creating a slice
a slice just like with an array we can also do
just like with an array we can also do an empty slice
an empty slice assignment like this
assignment like this or
or using
using this alternative syntax we can also
this alternative syntax we can also create a slice with this syntax
create a slice with this syntax so now we're actually saving user
so now we're actually saving user information in the bookings list let's
information in the bookings list let's actually clean this up before moving on
actually clean this up before moving on and instead let us
and instead let us print
all the bookings in the application
like this and we actually need printf
and we actually need printf and that's our cleaned up application
and that's our cleaned up application code
now even though we are saving the data of the list of users who booked the
of the list of users who booked the ticket we only always have just one user
ticket we only always have just one user because when we run the application we
because when we run the application we enter information get the ticket and the
enter information get the ticket and the application exits
application exits now of course in real life this would be
now of course in real life this would be a web application with a ui and a
a web application with a ui and a database connected to it where multiple
database connected to it where multiple people can book
people can book at the same time from their browsers and
at the same time from their browsers and the bookings will be persisted in a
the bookings will be persisted in a database
database but in our case we have a command line
but in our case we have a command line interface application so we're using our
interface application so we're using our application only through the terminal so
application only through the terminal so what we're going to do is create a
what we're going to do is create a constant loop where the application
constant loop where the application keeps asking for another ticket booking
keeps asking for another ticket booking after one booking is done
after one booking is done to simulate booking a ticket multiple
to simulate booking a ticket multiple times for different users and loops
times for different users and loops which is a concept that you may already
which is a concept that you may already know from other languages is basically
know from other languages is basically used whenever we need to repeat the same
used whenever we need to repeat the same logic multiple times
logic multiple times now in go specifically loops are
now in go specifically loops are actually simplified you don't have
actually simplified you don't have different types of loops like while loop
different types of loops like while loop and do while loop for each loop and so
and do while loop for each loop and so on you just have one
on you just have one loop which is a for loop and you can use
loop which is a for loop and you can use it for all the different use cases so
it for all the different use cases so basically you have for loop with
basically you have for loop with different types
different types our first case is
our first case is super simple use case for a for loop
super simple use case for a for loop which is that we just want to allow
which is that we just want to allow booking over and over again
booking over and over again so after the welcome message
so after the welcome message the logic
the logic which basically asks for user input and
which basically asks for user input and then books the tickets
then books the tickets and then prints out the summary of the
and then prints out the summary of the booking
booking need to be repeated so right here at the
need to be repeated so right here at the beginning of this logic we're going to
beginning of this logic we're going to write 4 so that's the beginning of a for
write 4 so that's the beginning of a for loop
loop and the syntax of a for loop is curly
and the syntax of a for loop is curly braces so whatever we put within those
braces so whatever we put within those curly braces gets repeated in this loop
curly braces gets repeated in this loop so i'm going to take this whole thing
and put it inside the for loop and let's actually fix the
and let's actually fix the indentation like this
indentation like this so we put that logic inside the for
so we put that logic inside the for loops block and for each line we have
loops block and for each line we have basically
basically indentations
indentations like this
like this so that's it this will basically
so that's it this will basically keep asking for a new booking
keep asking for a new booking after one booking is done and to test
after one booking is done and to test that
that let's run the application
and now immediately after we got the output of the booking first of all these
output of the booking first of all these three lines
three lines right here so we have 46 tickets
right here so we have 46 tickets remaining and this is one booking in our
remaining and this is one booking in our bookings list and immediately after that
bookings list and immediately after that it asks for another user's input and
it asks for another user's input and let's
let's fill it out let's do nicole
fill it out let's do nicole smith
smith and
email address and let's say she books three tickets
three tickets and as you see
and as you see the remaining tickets got updated from
the remaining tickets got updated from 46 to 43. right so minus three tickets
46 to 43. right so minus three tickets and now we have
and now we have two bookings in our bookings list the
two bookings in our bookings list the first user and the second user and we
first user and the second user and we can do this basically indefinitely for
can do this basically indefinitely for as many users as we want so to break the
as many users as we want so to break the application
application you can do control
you can do control c
c and this will basically interrupt and
and this will basically interrupt and stop the application
stop the application but of course when we start the
but of course when we start the application
application again it will start from scratch right
again it will start from scratch right so the bookings variable as well as
so the bookings variable as well as remaining tickets variable of course
remaining tickets variable of course gets updated while the application is
gets updated while the application is running right after each rerun
running right after each rerun everything gets reset
now let's do one more thing here at the end of
at the end of each booking we're printing out the list
each booking we're printing out the list of
of users who already bought the tickets and
users who already bought the tickets and we're printing out their first names and
we're printing out their first names and last names
last names but let's say we want to give our users
but let's say we want to give our users a little bit of privacy and instead of
a little bit of privacy and instead of printing their full names we want to
printing their full names we want to only print their first names to display
only print their first names to display the bookings with a little bit of
the bookings with a little bit of privacy so basically we want to go
privacy so basically we want to go through our bookings list
through our bookings list our full names bookings slice
our full names bookings slice and for each entry
and for each entry of the full name we want to extract only
of the full name we want to extract only the first name part and then print only
the first name part and then print only the first name
the first name again we're doing the same thing over
again we're doing the same thing over and over again to different elements of
and over again to different elements of the bookings list so it's a loop but
the bookings list so it's a loop but instead of an indefinite loop like the
instead of an indefinite loop like the one we're using here
one we're using here that basically never ends
that basically never ends we want to loop through a specific list
we want to loop through a specific list of elements
of elements so let's see how we can do that first of
so let's see how we can do that first of all let's define a slice for only the
all let's define a slice for only the first names
first names let's call it first names
let's call it first names and let's use the shortcut syntax for
and let's use the shortcut syntax for this
this so this is going to be a slice of first
so this is going to be a slice of first names which are strings and we are
names which are strings and we are starting with an
starting with an empty list now when i save of course we
empty list now when i save of course we get an error because we're not using it
get an error because we're not using it next what we're going to do is we're
next what we're going to do is we're going to
going to loop through or iterate through
loop through or iterate through our bookings list
our bookings list grabbing one element at a time and to
grabbing one element at a time and to iterate through a list
iterate through a list we have a pretty simple syntax actually
we have a pretty simple syntax actually we have four again
we have four again for loop and while we are iterating
for loop and while we are iterating through this list we get two values for
through this list we get two values for each iteration first we get an index and
each iteration first we get an index and you learn the index from the arrays it
you learn the index from the arrays it is basically a position of the element
is basically a position of the element in the list this is the first element
in the list this is the first element second element and so on so we get the
second element and so on so we get the index for each iteration and we get the
index for each iteration and we get the element itself and we can call this
element itself and we can call this element whatever we want it's like
element whatever we want it's like defining a variable let's call it
defining a variable let's call it booking
booking because we have a bookings list so each
because we have a bookings list so each element inside will be a booking
element inside will be a booking then we have a syntax of colon
then we have a syntax of colon equals
equals and here we define
and here we define what
what list are we actually iterating and
list are we actually iterating and getting these two values from which is
getting these two values from which is bookings
bookings so we are iterating through bookings and
so we are iterating through bookings and to iterate through a slice we need a
to iterate through a slice we need a range expression
range expression range allows us to iterate over elements
range allows us to iterate over elements in different data structures not just
in different data structures not just arrays or slices but for slices and
arrays or slices but for slices and arrays specifically it gives us back the
arrays specifically it gives us back the index and value for each element
index and value for each element so this basically defines the whole
so this basically defines the whole logic of go through
logic of go through this list and for each iteration give us
this list and for each iteration give us index
index and the element value and at the end we
and the element value and at the end we have curly braces for defining logic for
have curly braces for defining logic for our for loop so basically we have a for
our for loop so basically we have a for loop inside another for loop so inside
loop inside another for loop so inside these curly braces we have access to
these curly braces we have access to each element
each element stored in a booking variable
stored in a booking variable and
and index of that variable one by one so the
index of that variable one by one so the booking variable has a full name like
booking variable has a full name like nicole smith with a space character
nicole smith with a space character between and in order to get the nicole
between and in order to get the nicole the first name we can simply split the
the first name we can simply split the whole string on a space character using
whole string on a space character using goes built-in function called fields
like this and the fields function comes from
and the fields function comes from strings package
strings package so this will take our full name string
so this will take our full name string split it on
split it on empty space and gives us a slice of
empty space and gives us a slice of strings separated by space
strings separated by space which in this case is nicole and smith
which in this case is nicole and smith two values so a slice with two elements
two values so a slice with two elements and we're gonna save that into a
and we're gonna save that into a variable called names
variable called names so names will basically be an array
so names will basically be an array containing two elements the first name
containing two elements the first name and the last name and you learned to get
and the last name and you learned to get the first element of an array or slice
the first element of an array or slice we just use index 0
we just use index 0 and that's going to be our first name
and that's going to be our first name very easy now of course we're using a
very easy now of course we're using a package and its function so we need to
package and its function so we need to import that package and this is actually
import that package and this is actually one of the cases that i mentioned at the
one of the cases that i mentioned at the beginning if you want some functionality
beginning if you want some functionality of go you probably will not know by hard
of go you probably will not know by hard in which package you have such a
in which package you have such a functionality available and what is the
functionality available and what is the name of the function so of course in
name of the function so of course in this case you just google how to
this case you just google how to separate strings on space or something
separate strings on space or something similar and you get results probably
similar and you get results probably from ghost
from ghost official documentation
official documentation that references
that references this example so let's go ahead and
this example so let's go ahead and import these strings package
import these strings package right here now here we're just importing
right here now here we're just importing one package we haven't actually needed
one package we haven't actually needed any other but if we want to import
any other but if we want to import multiple packages then we have to
multiple packages then we have to enclose it into
enclose it into brackets
brackets and each package
and each package should be on
should be on a new line like this
a new line like this and then close that bracket and there
and then close that bracket and there you go now if you scroll down you see a
you go now if you scroll down you see a bunch of
bunch of red lines here which are all about
red lines here which are all about variables that are declared but not used
variables that are declared but not used and we're going to fix those one by one
and we're going to fix those one by one first of all we need to save this first
first of all we need to save this first name in our first names slice right
name in our first names slice right because we're basically going through
because we're basically going through these bookings and we're collecting a
these bookings and we're collecting a list of first names in this
list of first names in this slice and to add an element to a slice
slice and to add an element to a slice remember we use the append function
remember we use the append function which has the slice variable inside and
which has the slice variable inside and the element that we are adding which is
the element that we are adding which is actually first name and we have to then
actually first name and we have to then assign it back
assign it back to the slice variable like this so again
to the slice variable like this so again we're defining a list variable here a
we're defining a list variable here a slice variable and then within this loop
slice variable and then within this loop one by one we're adding a first name to
one by one we're adding a first name to this first name slice so at the end of
this first name slice so at the end of the for loop when we use first names
the for loop when we use first names here it's going to have the list of all
here it's going to have the list of all the first names from the bookings list
the first names from the bookings list now we can actually
now we can actually spare us this line here
spare us this line here by just grabbing this value here and
by just grabbing this value here and using it directly
using it directly in the append
in the append so we don't need
so we don't need an additional variable like this
an additional variable like this so basically when the loop is
so basically when the loop is done collecting the first names we can
done collecting the first names we can print it out right here
print it out right here let's do
let's do the first names
of bookings are
are and then we have first
and then we have first names
names instead of the bookings
instead of the bookings now you see that we still have one error
now you see that we still have one error here that we need to fix before we can
here that we need to fix before we can run our application and that is
run our application and that is the index variable that we created here
the index variable that we created here is not being used because we don't
is not being used because we don't actually need this index
actually need this index in our logic but we can't just remove it
in our logic but we can't just remove it and just leave booking here
and just leave booking here it needs to be there because we are
it needs to be there because we are expecting two values here so we have to
expecting two values here so we have to save both of them in a variable so
save both of them in a variable so instead we can fix the problem by simply
instead we can fix the problem by simply using an underscore in its place which
using an underscore in its place which is known as a blank identifier in go
is known as a blank identifier in go underscores are used to identify
underscores are used to identify unused variables so basically we're
unused variables so basically we're saying there is a variable here but we
saying there is a variable here but we just want to ignore it
just want to ignore it because we don't need to use it and if i
because we don't need to use it and if i save this you see that error is gone and
save this you see that error is gone and that is because we're telling go that we
that is because we're telling go that we know that there is a variable defined
know that there is a variable defined here that we are explicitly not using
here that we are explicitly not using that's basically the idea of using
that's basically the idea of using underscore so now with these changes
underscore so now with these changes let's run our application again
let's run our application again and see that only first names get
and see that only first names get printed out
and you see that our application logic works pretty good we have updates in
works pretty good we have updates in tickets after every booking and
tickets after every booking and at the end of each booking we also get a
at the end of each booking we also get a list of first names printed out and
list of first names printed out and again you can quit the application using
again you can quit the application using control and c
great now we have two for loops in our but the first one the indefinite for
but the first one the indefinite for loop never ends it keeps asking for
loop never ends it keeps asking for the next booking but what if all 50
the next booking but what if all 50 tickets are booked out we need to end
tickets are booked out we need to end the application and say that conference
the application and say that conference is sold out so after every booking we
is sold out so after every booking we need to check if the remaining tickets
need to check if the remaining tickets is zero
is zero and if it is we end the application
and if it is we end the application otherwise we let it continue and we do
otherwise we let it continue and we do that using
that using if else checks which is a concept you
if else checks which is a concept you have in all programming languages and is
have in all programming languages and is super easy
so let's see how it works so at the end of the booking
of the booking within our indefinite for loop
within our indefinite for loop right here we make the check to see if
right here we make the check to see if the remaining tickets is zero so no
the remaining tickets is zero so no tickets are left so we start with if
tickets are left so we start with if keyword and the expression after the if
keyword and the expression after the if keyword is called a condition like
keyword is called a condition like remaining tickets
remaining tickets equals zero and the data type of such
equals zero and the data type of such conditional statement is a boolean true
conditional statement is a boolean true or false
or false so either this
so either this statement is true remaining tickets is
statement is true remaining tickets is really zero or it's false so we're
really zero or it's false so we're telling the program if this condition is
telling the program if this condition is true then execute the code within these
true then execute the code within these curly braces or within the if statement
curly braces or within the if statement block if this condition is not true
block if this condition is not true then skip the execution of whatever code
then skip the execution of whatever code is defined here and skip to the next
is defined here and skip to the next line which in our case is the next
line which in our case is the next iteration of our for loop
iteration of our for loop so if the remaining tickets is zero we
so if the remaining tickets is zero we want to basically end the program so
want to basically end the program so here is going to be logic for
here is going to be logic for quitting the application
quitting the application so first let's actually print out
so first let's actually print out a message
a message for the user saying
for the user saying something like our conference
is booked out come back
come back next year
next year and after that we end the application
and after that we end the application how do we do that we basically break the
how do we do that we basically break the loop
loop using
using break keyword so this will basically end
break keyword so this will basically end the loop which means the application
the loop which means the application execution is over because there is
execution is over because there is nothing
nothing after the for loop right application
after the for loop right application ends
ends so as i said this
so as i said this expression here
expression here or the value of
or the value of this expression
this expression is of a boolean data type so we should
is of a boolean data type so we should have a boolean type keyword for that and
have a boolean type keyword for that and be able to create variables of that type
be able to create variables of that type as well right just like for other data
as well right just like for other data types so i could actually take this
types so i could actually take this whole expression
and save it into a variable which we can call
which we can call no tickets
no tickets remaining
remaining which is of a boolean type
which is of a boolean type and then we can use this
and then we can use this variable as a conditional of the if
variable as a conditional of the if statement
statement again with an alternative syntax we can
write this expression like this and by the way note the syntax for
and by the way note the syntax for double equal signs here instead of
double equal signs here instead of one equal sign so one equal sign is for
one equal sign so one equal sign is for assigning values to variables
assigning values to variables double equal sign is for comparing
double equal sign is for comparing two values to each other again nothing
two values to each other again nothing specific to go this is actually same in
specific to go this is actually same in other programming languages now since
other programming languages now since we're using this
we're using this variable only once here there's actually
variable only once here there's actually no need to save this expression into a
no need to save this expression into a separate variable so i'm going to
separate variable so i'm going to change it back
change it back to before
and leave it directly in the if statement so let's actually test that
statement so let's actually test that our logic works and the application ends
our logic works and the application ends when users have booked all 50 tickets
when users have booked all 50 tickets so let's run the application
so let's run the application provide the data
provide the data and let's actually take all 50 tickets
and let's actually take all 50 tickets at once
at once like this
like this and as you see after it printed the
and as you see after it printed the first names of bookings
first names of bookings right here we went to the next line so
right here we went to the next line so that remaining tickets equals 0 is true
that remaining tickets equals 0 is true so it
so it so this condition was true and because
so this condition was true and because of that it actually executed these two
of that it actually executed these two lines
lines and it printed out our conference is
and it printed out our conference is booked out come back next year and it
booked out come back next year and it broke out of the loop which ended the
broke out of the loop which ended the program now this makes sure that the
program now this makes sure that the program ends when all tickets are booked
program ends when all tickets are booked but what if a user wants to book more
but what if a user wants to book more tickets than available so what if i
tickets than available so what if i typed 52 instead of 50. let's see what
typed 52 instead of 50. let's see what would happen in this case
would happen in this case with our application
with our application so let's run it again
and i'm going to book 52 tickets and this is the output first of all we
and this is the output first of all we have
have this weird number of tickets remaining
this weird number of tickets remaining and second the application didn't end it
and second the application didn't end it actually continues to ask for
actually continues to ask for another user input so as you see our
another user input so as you see our application cannot handle when user
application cannot handle when user wants to book more than available number
wants to book more than available number of tickets
of tickets and the reason why application didn't
and the reason why application didn't end even though we exceeded the ticket
end even though we exceeded the ticket amount is because the remaining tickets
amount is because the remaining tickets is not zero anymore it's this number
is not zero anymore it's this number here that's why these two lines were not
here that's why these two lines were not executed so let's fix this issue and to
executed so let's fix this issue and to do that before the booking happens
do that before the booking happens right here where we take the remaining
right here where we take the remaining tickets and we deduct
tickets and we deduct the user tickets from it before that
the user tickets from it before that even happens we need to
even happens we need to check so we need another if statement
check so we need another if statement to check whether user tickets
to check whether user tickets is
is greater than the remaining tickets so if
greater than the remaining tickets so if user is trying to book more tickets than
user is trying to book more tickets than is available again very easy
is available again very easy we have if and then condition which says
we have if and then condition which says user tickets is
user tickets is more than
more than remaining tickets
remaining tickets right
right so this is going to be an invalid input
so this is going to be an invalid input from the user so we need to tell the
from the user so we need to tell the user
user something like we only have
something like we only have this many tickets
this many tickets remaining
remaining so you can't
so you can't book
so many tickets and let's substitute those
and let's substitute those values so we have
values so we have remaining tickets and this is the user
remaining tickets and this is the user tickets that they're trying to book
tickets that they're trying to book so we inform the user about their wrong
so we inform the user about their wrong input
input but we also have to end the program
but we also have to end the program because if this is true then all this
because if this is true then all this rest of the code should not be executed
rest of the code should not be executed right the ticket should not be booked so
right the ticket should not be booked so same is
right here we break from the loop which ends the
break from the loop which ends the program so this break here will
program so this break here will basically tell go to skip execution of
basically tell go to skip execution of the rest of the code in the iteration
the rest of the code in the iteration and
and stop the loop
stop the loop so all of these will be skipped so let's
so all of these will be skipped so let's test our logic
and try with 52 again
try with 52 again and as you see
and as you see the program says we only have 50 tickets
the program says we only have 50 tickets remaining so you can't book 52 tickets
remaining so you can't book 52 tickets and as you see none of the
and as you see none of the next lines gets executed and the program
next lines gets executed and the program exits so now we are handling an invalid
exits so now we are handling an invalid input from the user to protect our
input from the user to protect our application from the outcome that we saw
application from the outcome that we saw previously now let's say
previously now let's say we don't want to end the application if
we don't want to end the application if user wants to book more tickets than
user wants to book more tickets than remaining we want to allow them to try
remaining we want to allow them to try to book again with the corrected number
to book again with the corrected number of tickets so we don't want to stop the
of tickets so we don't want to stop the for loop completely with break we want
for loop completely with break we want to tell the user hey you're trying to
to tell the user hey you're trying to book an incorrect number of tickets so
book an incorrect number of tickets so please try again so we want to skip all
please try again so we want to skip all of these to the next iteration of the
of these to the next iteration of the for loop instead of breaking out of the
for loop instead of breaking out of the for loop completely and we can do that
for loop completely and we can do that also very easily
also very easily using another instruction called
using another instruction called continue
continue so instead of break
so instead of break we say continue to the next iteration so
we say continue to the next iteration so continue just like break we'll skip all
continue just like break we'll skip all of this but instead of ending the loop
of this but instead of ending the loop it will basically go to the next
it will basically go to the next iteration of the loop so let's try that
iteration of the loop so let's try that as well
let's do 52 again
52 again and you see the message gets printed out
and you see the message gets printed out you can't book so many tickets but it
you can't book so many tickets but it skips to the next iteration and it
skips to the next iteration and it starts with enter your first name again
starts with enter your first name again so user has another chance to enter
so user has another chance to enter correct amount so this makes our
correct amount so this makes our application a little bit more
application a little bit more user-friendly
now what if we wanted to check for the reverse condition and check if user
reverse condition and check if user wants to book
wants to book less tickets than available or exactly
less tickets than available or exactly the same number how could we do that
the same number how could we do that first we change the expression to less
first we change the expression to less than or equal so user tickets is either
than or equal so user tickets is either exactly same as remaining tickets or is
exactly same as remaining tickets or is less and we say if this condition is
less and we say if this condition is true so it's a valid input from the user
true so it's a valid input from the user then everything is great they can book
then everything is great they can book the ticket so
the ticket so this whole logic here can be executed so
this whole logic here can be executed so instead of these two
lines i'm going to put this outside of the
the if
if block
block so instead
so instead this logic will be executed
this logic will be executed so we are reversing the check and don't
so we are reversing the check and don't forget to fix the indentation here so if
forget to fix the indentation here so if this condition is true
this condition is true then
then this logic should be executed which
this logic should be executed which actually books the tickets
actually books the tickets now what about this code here where does
now what about this code here where does this logic go well after the if block is
this logic go well after the if block is finished
finished we add
we add an else statement
an else statement which says otherwise
which says otherwise so if this is not true
so if this is not true it's false in that case execute code in
it's false in that case execute code in this block
and that's where this logic will go so basically either at any iteration
so basically either at any iteration either the if block will get executed or
either the if block will get executed or else block right
else block right so this is an if else statement
so this is an if else statement and this basically logic wise does
and this basically logic wise does exactly the same as before we just
exactly the same as before we just changed
changed the condition here
the condition here and because only one of those blocks
and because only one of those blocks will be executed we don't need the
will be executed we don't need the continue part here to skip
continue part here to skip the booking logic right because the
the booking logic right because the booking logic is in its own
booking logic is in its own block so say so let's move the continue
block so say so let's move the continue and save and if i test this again
and try 52 you will see the error message so this
you will see the error message so this line was executed the else block
line was executed the else block basically and without the continue
basically and without the continue keyword it skipped to the next iteration
keyword it skipped to the next iteration because that's actually the next line of
because that's actually the next line of the code after the else block
now let's say we wanted to do something different if the user tickets and
different if the user tickets and remaining tickets were exactly
remaining tickets were exactly equal so if that was the case we wanted
equal so if that was the case we wanted to do something completely different
to do something completely different than what we're doing here or here so
than what we're doing here or here so where could we put this logic in that
where could we put this logic in that case we would split up this condition so
case we would split up this condition so here we would say if user tickets is
here we would say if user tickets is less than remaining tickets then do
less than remaining tickets then do whatever is defined here otherwise
whatever is defined here otherwise else
else if
if user tickets is exactly equal to
user tickets is exactly equal to remaining tickets
then do something else
do something else and finally
if none of these are true so this is false and
false and this is also false
this is also false then execute the else block and you can
then execute the else block and you can have as many else if statements in
have as many else if statements in between if and else as you want but you
between if and else as you want but you can only have one if statement and one
can only have one if statement and one final else statement now let's revert
final else statement now let's revert this because we're not doing anything
different here and let's revert back to our if else
and let's revert back to our if else statement
now there is another place where we use conditionals
conditionals that are true or false
that are true or false and that's in for loops so in addition
and that's in for loops so in addition to looping through a list
to looping through a list like this we can also say
like this we can also say execute the code in a loop for as long
execute the code in a loop for as long as a specific condition is true like
as a specific condition is true like execute code in this block
execute code in this block within this for loop
within this for loop for as long as remaining
for as long as remaining tickets is more than zero or as long as
tickets is more than zero or as long as the size of the bookings list is less
the size of the bookings list is less than 50 or even a combination of both
than 50 or even a combination of both like this
so we can use the same conditions that we saw in ifall statements
we saw in ifall statements as the for loop conditions
as the for loop conditions and tell our program to execute whatever
and tell our program to execute whatever code is inside that for loop as long as
code is inside that for loop as long as this condition is true as soon as it
this condition is true as soon as it becomes false the for loop execution is
becomes false the for loop execution is over now you may be thinking at this
over now you may be thinking at this point why didn't we have any condition
point why didn't we have any condition in our infinite for loop why doesn't it
in our infinite for loop why doesn't it say anything well since the conditions
say anything well since the conditions can be true or false an infinite loop
can be true or false an infinite loop can be written by using condition true
can be written by using condition true so basically hard coding aesthetic true
so basically hard coding aesthetic true will make this loop an infinite loop and
will make this loop an infinite loop and that's what we have and whenever we have
that's what we have and whenever we have that we can just leave out the condition
that we can just leave out the condition and have
and have for loop with no condition and that's
for loop with no condition and that's going to be the same as
going to be the same as saying for true and that's why we don't
saying for true and that's why we don't have to explicitly specify condition but
have to explicitly specify condition but again as i said if you want to write a
again as i said if you want to write a for loop that only runs as long as a
for loop that only runs as long as a specific condition is true you can
specific condition is true you can define that condition right here
another common use case for if else statements is user input validation in
statements is user input validation in our application we are allowing users to
our application we are allowing users to enter their data but users don't always
enter their data but users don't always enter data correctly either
enter data correctly either intentionally or unintentionally and we
intentionally or unintentionally and we developers must make sure that our
developers must make sure that our application doesn't crash when user puts
application doesn't crash when user puts in bad input so we have to make sure
in bad input so we have to make sure that our application is so robust that
that our application is so robust that it can actually handle any type of bad
it can actually handle any type of bad user input and the way to do that is to
user input and the way to do that is to always check whether the user input
always check whether the user input contains valid information any
contains valid information any unexpected values and so on so in our
unexpected values and so on so in our case let's check a couple of things in
case let's check a couple of things in user input that we're expecting so these
user input that we're expecting so these are the four pieces of data that we are
are the four pieces of data that we are getting from the user and we want to
getting from the user and we want to check all of those first let's check
check all of those first let's check that the names that user provides are
that the names that user provides are valid the first name and last name and
valid the first name and last name and let's say the valid name for us is a
let's say the valid name for us is a string with at least two characters now
string with at least two characters now if the user provided a wrong name this
if the user provided a wrong name this would not crash the application but we
would not crash the application but we want to make sure that users are not
want to make sure that users are not spamming our application and are
spamming our application and are actually giving correct information at
actually giving correct information at least we try to partially check that and
least we try to partially check that and again we have to do the validation part
again we have to do the validation part before
before the booking logic gets executed right
the booking logic gets executed right because
because if they entered invalid data we don't
if they entered invalid data we don't allow the booking
allow the booking so right here let's check that first
so right here let's check that first name and last name length is at least
name and last name length is at least two characters
two characters but we're not going to do anything with
but we're not going to do anything with it yet
it yet we will just save it into a variable and
we will just save it into a variable and use it later now to check the length of
use it later now to check the length of a string we have the built-in function
a string we have the built-in function called len length which you already
called len length which you already learned from arrays and slices so for
learned from arrays and slices so for arrays and slices this checks the size
arrays and slices this checks the size of the list for strings it checks the
of the list for strings it checks the size of the characters so how many
size of the characters so how many characters are in a string
characters are in a string so
so first name length
first name length should be at least
should be at least two so it can be two as well that's why
two so it can be two as well that's why we're going to do greater than or equal
we're going to do greater than or equal to two and the same should be true for
to two and the same should be true for the last name so in addition to that we
the last name so in addition to that we also want to
also want to validate last name in the same statement
validate last name in the same statement and we can do that or we can chain these
and we can do that or we can chain these two conditions using
two conditions using end
end characters again note the double
characters again note the double ampersand signs
ampersand signs so this basically says this condition
so this basically says this condition and
this condition so this is going to be check for last
so this is going to be check for last name
name and whatever value of this expression
and whatever value of this expression again assign it to a boolean variable
again assign it to a boolean variable and we're going to call it
and we're going to call it is valid
is valid name
again we can skip the boolean type because go can imply from the value that
because go can imply from the value that it's a boolean
it's a boolean type so we can save that
type so we can save that and we can also use the
and we can also use the alternative syntax like this so again if
alternative syntax like this so again if user entered the first name that is at
user entered the first name that is at least two characters long
least two characters long and last name which is also at least two
and last name which is also at least two characters long then this whole thing
characters long then this whole thing will be true and we're gonna assign the
will be true and we're gonna assign the true to is valid name variable now if
true to is valid name variable now if any one of those is false so if first
any one of those is false so if first name is valid but last name is not or
name is valid but last name is not or vice versa then this whole expression
vice versa then this whole expression will be also false and that false value
will be also false and that false value will then be assigned to is valid name
will then be assigned to is valid name variable now let's validate the email
variable now let's validate the email address
address and let's say for email address we want
and let's say for email address we want to make sure
to make sure they're not entering an invalid email
they're not entering an invalid email format so we're going to check that the
format so we're going to check that the value of email or the string
value of email or the string contains the it
contains the it sign now you already learned the strings
sign now you already learned the strings package
package from which we use this fields
from which we use this fields function
function and the same strings package actually
and the same strings package actually has
has a function called contains
that takes a string as a first input and then a character
as a first input and then a character or
or multiple characters that we want to
multiple characters that we want to search in that string
search in that string and this will actually give us
and this will actually give us a boolean result back
a boolean result back so if
so if the string
the string contains
contains this character or these characters then
this character or these characters then it will give us true back if not then
it will give us true back if not then it's going to be false
it's going to be false so we can call this
so we can call this is
is valid email
and assign this whole value to it so we assume if email user gave us
so we assume if email user gave us contains this character then it is a
contains this character then it is a valid email if not then it's not valid
valid email if not then it's not valid and finally let's check the user tickets
and finally let's check the user tickets and validate that
and validate that user
user didn't enter a number of tickets which
didn't enter a number of tickets which is negative or zero so it has to be
is negative or zero so it has to be positive number greater than zero
positive number greater than zero so again user tickets is more than zero
so again user tickets is more than zero will be a valid ticket count now we have
will be a valid ticket count now we have another
another check for the user tickets which is
check for the user tickets which is that it's a less than remaining ticket
that it's a less than remaining ticket so a user cannot book more tickets than
so a user cannot book more tickets than available so that's going to be another
available so that's going to be another validation for this input and we can
validation for this input and we can actually add that
actually add that right here
right here also with this end sign so both of these
also with this end sign so both of these expressions
expressions need to be true so that we have a valid
need to be true so that we have a valid user ticket if any one of those is wrong
user ticket if any one of those is wrong let's say user tickets is a positive
let's say user tickets is a positive number but it's
number but it's more than remaining tickets then it's
more than remaining tickets then it's going to be invalid input so let's call
going to be invalid input so let's call this is valid
this is valid ticket number
ticket number and here we have our
and here we have our user input validations so as i said we
user input validations so as i said we can chain multiple conditions like this
can chain multiple conditions like this with double end sign to make sure both
with double end sign to make sure both of these are true to give us a valid
of these are true to give us a valid ticket number we can also chain
ticket number we can also chain conditions with or instead of end
conditions with or instead of end let's say the conference is taking place
let's say the conference is taking place in two cities
in two cities singapore and london
singapore and london and user can choose which one
and user can choose which one they want to go to or which location
they want to go to or which location they want to attend so they can choose
they want to attend so they can choose between those two cities but they can't
between those two cities but they can't enter some random city that is not valid
enter some random city that is not valid so
so in that case we could have a check
in that case we could have a check is valid city
is valid city where let's say if we had the city as an
where let's say if we had the city as an input we would check if it's either
input we would check if it's either singapore
so city cannot have both of these values right it has to have either singapore or
right it has to have either singapore or london if it has some other value then
london if it has some other value then it is an invalid city but if it's valid
it is an invalid city but if it's valid then it should be
then it should be either
either or so in this case we chain this
or so in this case we chain this condition using or instead of
condition using or instead of int
int well sometimes we need to check whether
well sometimes we need to check whether the user did not enter a specific value
the user did not enter a specific value for example let's say we want to check
for example let's say we want to check is invalid city
which means user didn't enter
user didn't enter either singapore
either singapore so the city is not singapore
so the city is not singapore and
and it's also not
it's also not london
london so basically if both of these conditions
so basically if both of these conditions are true so the city
are true so the city the value of the city is not singapore
the value of the city is not singapore and is not london then is invalid city
and is not london then is invalid city is true
is true so this here is a negation or not equal
so this here is a negation or not equal and it may be a little bit confusing
and it may be a little bit confusing than positive statements like equal or
than positive statements like equal or greater than etc so if this is
greater than etc so if this is more confusing than the previous
more confusing than the previous statement then what you could also do
statement then what you could also do is revert this back to
is revert this back to is valid city and then
is valid city and then using that exclamation
using that exclamation mark you can
mark you can negate
negate the result of this so basically this
the result of this so basically this statement with exclamation mark is valid
statement with exclamation mark is valid city is exactly the same as the negative
city is exactly the same as the negative check that i just showed you and you
check that i just showed you and you could use this in the if statement of
could use this in the if statement of course like this
course like this okay now let's clean up all these
okay now let's clean up all these examples
and go back to our user input
user input checks we have saved all these checks in
checks we have saved all these checks in variables so now it's time to use those
variables so now it's time to use those variables in the if statement and
variables in the if statement and execute the booking
execute the booking only if all the user input values are
only if all the user input values are valid and skip the booking if at least
valid and skip the booking if at least one of those
one of those user
user inputs are invalid
inputs are invalid so if name and email are correct but the
so if name and email are correct but the ticket number is invalid of course we
ticket number is invalid of course we want to skip the booking so in the if
want to skip the booking so in the if statement we check
statement we check if is valid
if is valid name
name is true
is true and
and is valid email is also true
is valid email is also true and
and is valid ticket number is also true so
is valid ticket number is also true so all three have to be true in order to
all three have to be true in order to execute the booking so again we're
execute the booking so again we're chaining this with end
chaining this with end symbols which means all of these three
symbols which means all of these three have to be true in order to execute the
have to be true in order to execute the booking and if i save this we also get
booking and if i save this we also get rid of the error and if any of the user
rid of the error and if any of the user inputs is wrong we're going to
inputs is wrong we're going to inform the users about that saying
using a simple message that says your input
your input data is
data is invalid
invalid try again
try again let's save it and let's actually test
let's save it and let's actually test that our validation logic works
that our validation logic works so i'm going to put in
so i'm going to put in first name which is just one character
and all the other stuff are correct
all the other stuff are correct as you see we get invalid data input
as you see we get invalid data input let's now try
let's now try a wrong email address
without the add sign and again invalid input data and you can
and again invalid input data and you can also test ticket number and so on
also test ticket number and so on so now we have some kind of protection
so now we have some kind of protection in our application against
in our application against bad user input as i said the bad or
bad user input as i said the bad or invalid user input can be intentional or
invalid user input can be intentional or unintentional sometimes
unintentional sometimes users accidentally enter wrong
users accidentally enter wrong information so we could optimize our
information so we could optimize our application to tell the user
application to tell the user what they actually entered incorrectly
what they actually entered incorrectly so they can correct it so instead of
so they can correct it so instead of this generic message here which says
this generic message here which says your input data is invalid we're going
your input data is invalid we're going to say exactly
to say exactly what they entered wrong
what they entered wrong so right here we're going to have
so right here we're going to have if statements that check which of the
if statements that check which of the inputs were actually wrong
inputs were actually wrong so we're going to say if
so we're going to say if is valid name
is valid name is not true
is not true remember the negation with exclamation
remember the negation with exclamation mark so if
mark so if name is invalid so this translates to is
name is invalid so this translates to is invalid name
invalid name in that case
in that case we're going to print
first name or last name
or last name you entered
we're going to do the same for email and we're going to say if
email and we're going to say if email is invalid
or if is valid email is not true
is valid email is not true we're going to print
we're going to print a message that says
a message that says email
email address you entered
does not contain
contain at sign
and finally is
is not valid ticket number
not valid ticket number we're going to say
we're going to say number of
number of tickets you entered is invalid
tickets you entered is invalid and we don't need this generic message
and we don't need this generic message here and note that we don't have else
here and note that we don't have else here we just have if statements because
here we just have if statements because we want each of these statements to be
we want each of these statements to be executed because they might have entered
executed because they might have entered all these data wrong wrong name wrong
all these data wrong wrong name wrong email wrong ticket number so in that
email wrong ticket number so in that case we want to say your name is wrong
case we want to say your name is wrong your email is wrong the number of
your email is wrong the number of tickets is invalid if this were else if
tickets is invalid if this were else if conditions like this
conditions like this and user had entered
and user had entered invalid name then this would be true and
invalid name then this would be true and this line would be executed and
this line would be executed and the else blocks will be skipped because
the else blocks will be skipped because as i said
as i said with if else or if else if statements
with if else or if else if statements only one of the blocks gets executed not
only one of the blocks gets executed not all of them or not multiple of them
all of them or not multiple of them that's why we're gonna
that's why we're gonna revert it back to if statements
revert it back to if statements and
and now let's actually try to input a bunch
now let's actually try to input a bunch of wrong data
of wrong data like this
like this wrong email
wrong email number of tickets zero
number of tickets zero and we get
and we get all of these messages it says the name
all of these messages it says the name is too short
is too short email is invalid
email is invalid and number of tickets is also invalid so
and number of tickets is also invalid so now user knows exactly what they entered
now user knows exactly what they entered wrong
wrong so as you see if else statements are
so as you see if else statements are super important in applications because
super important in applications because they basically control the whole
they basically control the whole application flow it's like a decision
application flow it's like a decision tree right we do different things based
tree right we do different things based on different conditions
on different conditions now let's see another concept in
now let's see another concept in programming which is similar to e-file
programming which is similar to e-file statements which is switch statement
statements which is switch statement let's say our conference is held in six
let's say our conference is held in six different cities
different cities and for most of the cities we have
and for most of the cities we have different booking processes and the data
different booking processes and the data we are asking from users so the
we are asking from users so the application logic is basically different
application logic is basically different based on for which city you want to book
based on for which city you want to book the conference ticket so at the
the conference ticket so at the beginning of the application we need to
beginning of the application we need to check which city user selected and based
check which city user selected and based on that selection we then execute a
on that selection we then execute a different code block now if we have to
different code block now if we have to check for six different cities having
check for six different cities having six if else statements
six if else statements may not be optimal
may not be optimal and for such cases we have switch
and for such cases we have switch statements
statements now we're not going to execute this code
now we're not going to execute this code so i'm just going to show you the
so i'm just going to show you the example syntax right here of how switch
example syntax right here of how switch statements actually look like so let's
statements actually look like so let's say we have this city
say we have this city variable that user basically selects and
variable that user basically selects and let's say the user selected london
let's say the user selected london and right here we need to check which of
and right here we need to check which of the six cities
the six cities user wants to book tickets for so first
user wants to book tickets for so first we have the switch keyword that checks
we have the switch keyword that checks the value of city and here we have
the value of city and here we have multiple cases so case one is
multiple cases so case one is city value equals
city value equals new york
new york in which case
in which case we want to
we want to execute code
for booking
booking new york
new york conference tickets
conference tickets another case or another possible value
another case or another possible value for
for city
city is
is singapore
singapore and again
and again here we would execute code for
here we would execute code for booking
booking a singapore conference tickets
a singapore conference tickets in other case
in other case let's say we have london
let's say we have london again some code here
and let's do mexico city and finally
and finally hong kong
and after each case we have we need the colon
we need the colon so all these are possible values for
so all these are possible values for city
city so these are where the conferences are
so these are where the conferences are held but as i said users sometimes enter
held but as i said users sometimes enter invalid data so we also need to
invalid data so we also need to handle
handle when
when the city has none of these values and
the city has none of these values and that's going to be a default case
that's going to be a default case in the switch statement so basically
in the switch statement so basically when none of these are true
when none of these are true then we execute a code block
then we execute a code block which let's say prints out
which let's say prints out no valid city selected
no valid city selected so that's like the else in the e-file
so that's like the else in the e-file statement
statement so switch just like e-files basically
so switch just like e-files basically controls
controls the application flow and based on a
the application flow and based on a value of whatever variable we pass into
value of whatever variable we pass into switch we execute a different logic in
switch we execute a different logic in our application
our application now let's say
now let's say the booking logic for london and berlin
the booking logic for london and berlin is the same
is the same as well as booking logic for singapore
as well as booking logic for singapore and hong kong
and hong kong is also the same so in this case we
is also the same so in this case we don't want to
don't want to duplicate the code
duplicate the code instead we want to consolidate those two
instead we want to consolidate those two cases
cases saying if
saying if the city is london or berlin then
the city is london or berlin then execute this code and we can also do
execute this code and we can also do that in switch statement
that in switch statement by
by listing all the possible values like
listing all the possible values like this
and this will be the same logic for london and berlin
for london and berlin and
and as i said
for these two cities as well
these two cities as well like this
like this so basically
so basically in switch statements you can also
in switch statements you can also consolidate multiple values and execute
consolidate multiple values and execute a certain logic for multiple values
a certain logic for multiple values so that's how switch statements work
so that's how switch statements work again let's clean this up
and get back to our booking logic
now our super simple application became already pretty crowded
already pretty crowded we have all this code in our main
we have all this code in our main function
function that keeps on growing so it would be
that keeps on growing so it would be nice to start cleaning it up by taking
nice to start cleaning it up by taking parts of the code that do one specific
parts of the code that do one specific thing
thing and putting them in functions
and putting them in functions with some descriptive name so we
with some descriptive name so we encapsulate a code block into its own
encapsulate a code block into its own container called a function give it a
container called a function give it a name that makes it immediately clear
name that makes it immediately clear what that code block does and use that
what that code block does and use that block of code simply by calling the
block of code simply by calling the function by its name so let's see how to
function by its name so let's see how to write functions in go well in fact we
write functions in go well in fact we have already created a function at the
have already created a function at the beginning which was the main function so
beginning which was the main function so the same way after the main function
the same way after the main function ends right here
ends right here that's the end of the main function
that's the end of the main function block
block we create another one
we create another one using a func keyword
using a func keyword then again name of the function and
then again name of the function and let's call this one greet
let's call this one greet users
users and after that we have again function
and after that we have again function block using the curly braces so each
block using the curly braces so each function has its own
function has its own block
block and when we call the function then
and when we call the function then whatever code is inside those curly
whatever code is inside those curly braces gets executed
braces gets executed like
like a print statement
which says welcome to our
to our conference so we have created a simple
conference so we have created a simple function that basically just prints out
function that basically just prints out welcome to our conference now when we
welcome to our conference now when we run our application this code will not
run our application this code will not get executed because when we create or
get executed because when we create or define a function it basically just
define a function it basically just stores whatever code is inside
stores whatever code is inside for later use but it doesn't actually
for later use but it doesn't actually execute it for that we need to
execute it for that we need to explicitly execute or call the function
explicitly execute or call the function inside the main function because this is
inside the main function because this is as i mentioned at the very beginning
as i mentioned at the very beginning this is the function that go will look
this is the function that go will look for to start the execution so if we
for to start the execution so if we create other functions
create other functions we have to explicitly call them
we have to explicitly call them inside the main function so that code
inside the main function so that code inside them gets executed
inside them gets executed and calling a function is super easy
and calling a function is super easy let's say right here at the beginning we
let's say right here at the beginning we want to
want to call grid users function that will then
call grid users function that will then print out the welcome message
so if we run our application we have this
this welcome to our conference which comes
welcome to our conference which comes from greet users function
from greet users function and then of course we have whatever we
and then of course we have whatever we define in the main
now let's say we want to greet users with the conference name instead of just
with the conference name instead of just a generic
a generic welcome to our conference so basically
welcome to our conference so basically the same way as we're doing right here
the same way as we're doing right here so how can we give the grid users
so how can we give the grid users function the value of the conference
function the value of the conference name variable which we defined here
name variable which we defined here well we can pass it as an input
well we can pass it as an input parameter so we can hand it over to
parameter so we can hand it over to greet user's function saying here is the
greet user's function saying here is the value of conference name variable
value of conference name variable you can use it inside your function
you can use it inside your function block in your code
by just passing it within the brackets
passing it within the brackets but we also need to tell the
but we also need to tell the function itself
function itself that it is expecting a parameter we can
that it is expecting a parameter we can just throw some parameters to a function
just throw some parameters to a function randomly we have to expect it explicitly
randomly we have to expect it explicitly here as well so in the function
here as well so in the function definition within the brackets
definition within the brackets we're going to define that parameter
we're going to define that parameter using
using either the same name as the variable
either the same name as the variable that we're using or we can also give it
that we're using or we can also give it a completely different name
a completely different name it's up to us so we can call it whatever
it's up to us so we can call it whatever we want and we also have to specify its
we want and we also have to specify its type because remember variables in go
type because remember variables in go have to have types so we're telling this
have to have types so we're telling this function you're expecting an input
function you're expecting an input parameter called conf name which is of
parameter called conf name which is of type string
type string so think of this as a variable inside a
so think of this as a variable inside a function this is very similar to
function this is very similar to doing this
doing this inside a function
inside a function and that's actually what happens in the
and that's actually what happens in the background when the function gets called
background when the function gets called and then you can use this
and then you can use this variable or this variable inside
variable or this variable inside this function block
this function block and that's what we're going to do we're
and that's what we're going to do we're going to say welcome to
going to say welcome to booking
booking application
application and use the conf name value
so now if we run the application and we forgot the new line here
as on this line so we basically extracted
extracted this code into a function
this code into a function so we don't need this one and let's
so we don't need this one and let's actually put
actually put the whole greeting logic into our grid
the whole greeting logic into our grid function so i'm going to take this
and in the grid users function let's edit right here and the same way
let's edit right here and the same way that we pass the conference name we also
that we pass the conference name we also need to pass
need to pass these two
these two values because we have to have them
values because we have to have them available within the function so we have
available within the function so we have to pass them as input parameters
to pass them as input parameters and as i said we can call these whatever
and as i said we can call these whatever we want
we want like conf tickets
like conf tickets which is integer
which is integer and
and let's call the other one remaining
let's call the other one remaining tickets which is
tickets which is u integer unsigned integer
like this and of course now whenever we call this function
call this function we have to pass all three parameters
we have to pass all three parameters otherwise we're gonna get an error like
otherwise we're gonna get an error like here it says
here it says not enough arguments so let's pass those
not enough arguments so let's pass those two values as well
two values as well first one is conference tickets
first one is conference tickets this value and then we have
this value and then we have the remaining tickets
save and the error is gone so we replaced these print
replaced these print lines with a function call
like this which makes our main function a little bit cleaner and now if we run
a little bit cleaner and now if we run the application we should actually get
the application we should actually get exactly the same output as before we had
exactly the same output as before we had the function
the function and as you see we have our welcome
and as you see we have our welcome statement
statement all the values are substituted
all the values are substituted everything looks fine
everything looks fine so we extracted first
so we extracted first group of code
group of code into a function and gave it some
into a function and gave it some descriptive name that says
descriptive name that says this will greet the users
this will greet the users now let's take the code for
now let's take the code for picking out the first names so this code
picking out the first names so this code block here and put it in a function
block here and put it in a function called
called print first names because that's what it
print first names because that's what it does right it
does right it goes through the bookings and it prints
goes through the bookings and it prints the first names of the people who booked
the first names of the people who booked the tickets so i'm gonna
the tickets so i'm gonna cut this whole thing out
cut this whole thing out so here we will call
so here we will call function
function print
print first names and right here we're going
first names and right here we're going to create that function with the name
to create that function with the name again descriptive name print
again descriptive name print first
first names
names again function block and all the code
again function block and all the code that i copied will go
that i copied will go inside
inside if i save again you'll see that
if i save again you'll see that we need some values
we need some values as an input because we don't have them
as an input because we don't have them available here so go doesn't know where
available here so go doesn't know where this bookings variable comes from it's
this bookings variable comes from it's not available inside this function so we
not available inside this function so we have to pass it as a parameter
have to pass it as a parameter and we're going to define it here
and we're going to define it here bookings is a slice of strings
bookings is a slice of strings so the type is going to be
so the type is going to be square brackets and string that's it
square brackets and string that's it and if i save this error will disappear
and if i save this error will disappear now we have to actually call this
now we have to actually call this function otherwise
function otherwise the first names will not be printed out
the first names will not be printed out so
function call and we have to pass bookings as a parameter
bookings as a parameter that's it
that's it we have extracted
we have extracted another block of code or another logic
another block of code or another logic into its own function
now let's say we wanted to print the first names actually in the main
first names actually in the main function so we only want to pick the
function so we only want to pick the first names
first names from the bookings slice
from the bookings slice in this function but the final printing
in this function but the final printing so this line here should actually be
so this line here should actually be done in the main function for whatever
done in the main function for whatever reason so instead of printing
reason so instead of printing the first names we want this function to
the first names we want this function to actually just return the first names to
actually just return the first names to the main function so that main can print
the main function so that main can print it itself so instead of this line we
it itself so instead of this line we want
want return
return first names
first names so return keyword as you see the
so return keyword as you see the highlight here
highlight here says that this function is doing some
says that this function is doing some logic and then returning a result
logic and then returning a result of that logic back to the main function
of that logic back to the main function and we have an error here because
and we have an error here because whenever we are returning something from
whenever we are returning something from a function we also have to specifically
a function we also have to specifically say that in the function definition that
say that in the function definition that we are returning a value of
we are returning a value of a certain type in our case first names
a certain type in our case first names is also
is also a slice of strings so
a slice of strings so that's what we're returning so note that
that's what we're returning so note that within those brackets we have the input
within those brackets we have the input parameters and outside
parameters and outside those brackets
those brackets we have
we have output parameters
output parameters with a type of the output we're
with a type of the output we're returning and this print line
returning and this print line should go back to
should go back to the main function
the main function and if i save this of course
and if i save this of course main function doesn't know this variable
main function doesn't know this variable because we should get that from this
because we should get that from this function right here and let's actually
function right here and let's actually rename this function now because it now
rename this function now because it now doesn't print the first names it just
doesn't print the first names it just returns or gets the first names
and whenever function actually returns something to us we can save that return
something to us we can save that return value into a variable
value into a variable and let's call this variable first names
and let's call this variable first names because
because that's what we need here
that's what we need here equals first names
equals first names is a result of
is a result of whatever get first names function gives
whatever get first names function gives us
us and that's it
and that's it so our function does its thing its logic
so our function does its thing its logic it gives us a result and then we take
it gives us a result and then we take that result in the main function
that result in the main function like this and do something with it like
like this and do something with it like print it out
print it out let's see what else can we extract here
let's see what else can we extract here another candidate for its own function
another candidate for its own function can be the user input validation so i'm
can be the user input validation so i'm going to take this logic and let's
going to take this logic and let's actually create
actually create another function called
another function called validate
validate user input
and again let's fix the indentation
fix the indentation like this
like this by now you already know how this works
by now you already know how this works we need to define all the variables that
we need to define all the variables that we're using here
we're using here we need to define them as input
we need to define them as input parameters so first name which is a
parameters so first name which is a string last name
string last name also a string
also a string email
email also a string
also a string and
and user tickets
user tickets which is integer
which is integer finally or it's actually you int and
finally or it's actually you int and finally remaining tickets
finally remaining tickets which is also
which is also you int and if i save
you int and if i save all these errors are gone
all these errors are gone and we're going to call this function
and we're going to call this function with all the input parameters we defined
with all the input parameters we defined so we have the first name
email user tickets and remaining tickets
however now we don't have these three variables
variables available in the main function anymore
available in the main function anymore that's why we have these errors here
that's why we have these errors here because it doesn't recognize these
because it doesn't recognize these variables and we have errors here as
variables and we have errors here as well so we need those three values
well so we need those three values actually available
actually available in the main function so we need to
in the main function so we need to return all three values back to the main
return all three values back to the main function
function well in most programming languages
well in most programming languages you cannot do that you cannot return
you cannot do that you cannot return multiple values from a function you can
multiple values from a function you can always return just one value
always return just one value but in go
but in go you can return any number of values you
you can return any number of values you want from a function
want from a function which i think is pretty cool because
which i think is pretty cool because there are many use cases for this
there are many use cases for this and it works the same way as returning
and it works the same way as returning just one value we just say return
just one value we just say return and we just list
and we just list any values or variables that we want to
any values or variables that we want to return
like this and of course
and of course the same way as with one return value we
the same way as with one return value we have to define
have to define the types the data types of all the
the types the data types of all the return values in order
return values in order which
which we do outside those parentheses
we do outside those parentheses and when we have multiple returns we
and when we have multiple returns we have to also enclose them in its own
have to also enclose them in its own separate parentheses so within this
separate parentheses so within this block we're going to define
block we're going to define the data types of these three values
the data types of these three values which are all boolean
which are all boolean true or false values so this is going to
true or false values so this is going to be boolean 1 boolean 2 volume 3.
be boolean 1 boolean 2 volume 3. so again
so again input values in the first parenthesis
input values in the first parenthesis input parameters
input parameters and then in the second one a list of
and then in the second one a list of output parameter types and now that
output parameter types and now that we're returning these three values it's
we're returning these three values it's time to grab them or collect them
time to grab them or collect them outside here
outside here and that is also pretty easy we can just
and that is also pretty easy we can just list them one by one like ease valid
list them one by one like ease valid name
name is valid email
is valid email is valid
is valid ticket number
save and there you go now all these three
three variables are available in the main
variables are available in the main function so
function so the errors are gone so let's check our
the errors are gone so let's check our code we have these three functions that
code we have these three functions that we created and our main function got
we created and our main function got smaller and maybe more descriptive now
smaller and maybe more descriptive now let's also extract the code for getting
let's also extract the code for getting user input in a function so i'm going to
user input in a function so i'm going to grab this whole code tool here
and save it into a separate function and let's call this
a separate function and let's call this get user input
fix the indentation and as you see get user input function doesn't need any
user input function doesn't need any input parameters because we're asking
input parameters because we're asking for input from the users so we don't
for input from the users so we don't need anything from the main function
need anything from the main function however
however inside the main function we need those
inside the main function we need those values because we're doing all the
values because we're doing all the processing based on whatever user
processing based on whatever user entered right so we have to actually
entered right so we have to actually return all these input
return all these input data
data back to the main
back to the main so
so return first name
email and use the tickets
use the tickets and again we have to
and again we have to specify the types
specify the types of those right here
of those right here so first name last name email and
so first name last name email and user tickets
user tickets and in the main
and in the main just like we did right here
we're gonna grab those values one by one so we have the first name
last name email and user tickets and if i save this
and if i save this you see
you see all the errors are gone because now we
all the errors are gone because now we have these four values available here as
have these four values available here as well
well and finally let's take the code for
and finally let's take the code for booking the application
booking the application actually this whole logic here
actually this whole logic here and also put it in its own function
and also put it in its own function and
logically we're going to call this function
function book
book ticket
and if i save you see a bunch of errors because we
you see a bunch of errors because we don't have these values available here
don't have these values available here so we need a lot of input parameters
so we need a lot of input parameters for this function
for this function so let's define them one by one
so let's define them one by one remaining tickets
bookings which is a slice of strings we have the first name
we have the first name last name
and finally we also need the conference name
we also need the conference name which is also
which is also string and if i save
string and if i save it all looks fine
it all looks fine when we call this function in the main
when we call this function in the main so this is where book ticket happens
so this is where book ticket happens we're going to pass all those
we're going to pass all those defined parameters
defined parameters which is a long list of
which is a long list of values
now here you may be wondering if i have to pass so many parameters to my
to pass so many parameters to my function does it make my code cleaner
function does it make my code cleaner that's a lot of repeated code because
that's a lot of repeated code because we're passing all these
we're passing all these same values
same values and parameters to different functions so
and parameters to different functions so to reduce this repetition a bit we can
to reduce this repetition a bit we can define variables that are shared among
define variables that are shared among multiple functions so variables that are
multiple functions so variables that are accessible both for main and
accessible both for main and other functions as well without having
other functions as well without having to pass them around like this so it
to pass them around like this so it makes sense to create those variables in
makes sense to create those variables in a place that lets multiple functions
a place that lets multiple functions including the main have access to them
including the main have access to them and these are called package level
and these are called package level variables and these are variables
variables and these are variables defined outside from all the functions
defined outside from all the functions so instead of defining these variables
so instead of defining these variables inside of the main we're going to take
inside of the main we're going to take them and instead define them outside
them and instead define them outside on a package level
on a package level like this
like this and now they're not only
and now they're not only accessible to main but also to all the
accessible to main but also to all the functions in this package
functions in this package now if i save this you see we have two
now if i save this you see we have two errors
errors and that is because the package level
and that is because the package level variables cannot be created using this
variables cannot be created using this syntax
syntax they need the
they need the syntax with var keyword
syntax with var keyword so if i save this you see the error is
so if i save this you see the error is gone we'll do the same here
gone we'll do the same here and that's it we can also take the
and that's it we can also take the put the constant
put the constant at the top like this
at the top like this so now as i said we don't have to pass
so now as i said we don't have to pass those variables to other functions from
those variables to other functions from main because
main because these functions also have access to them
these functions also have access to them directly so in the grid users function
directly so in the grid users function for example we were
for example we were passing
passing three of these variables as parameters
three of these variables as parameters now we don't need this anymore
now we don't need this anymore because
because grid users
grid users can access those
can access those variables directly so i'm going to
variables directly so i'm going to delete this
delete this and save and we have an error because
and save and we have an error because now the names of the variables have to
now the names of the variables have to be exactly
be exactly what is defined here right so conference
what is defined here right so conference name
name like this
like this conference
conference tickets
tickets and that's it we have no errors and no
and that's it we have no errors and no need to pass those values
need to pass those values as input parameters
as input parameters again makes the function execution much
again makes the function execution much cleaner
cleaner we also have the bookings array which is
we also have the bookings array which is defined on a package level so we don't
defined on a package level so we don't need to
need to pass that here as well
pass that here as well so i'm going to remove this
so i'm going to remove this from get first names
from get first names and
again everything works
works same thing right here validate user
same thing right here validate user input
input we're passing it remaining tickets as a
we're passing it remaining tickets as a variable which it doesn't need anymore
variable which it doesn't need anymore but it still needs those four variables
but it still needs those four variables obviously because they are still created
obviously because they are still created in the main function
in the main function and not available directly outside
and not available directly outside so let's go to
so let's go to validate user input
validate user input and remove
and remove this
this last
parameter and finally our book ticket function that has this long
book ticket function that has this long list of
list of parameters we can get rid of remaining
parameters we can get rid of remaining tickets
bookings and conference name as parameters because they are all defined
parameters because they are all defined here
and if i save everything looks fine again
now you may be thinking why not define all the variables at the top right here
all the variables at the top right here and then make them accessible everywhere
and then make them accessible everywhere in our functions well this would be a
in our functions well this would be a bad practice because generally you want
bad practice because generally you want to define a variable as locally as
to define a variable as locally as possible so basically create a variable
possible so basically create a variable where you need it so if you need a
where you need it so if you need a variable only inside a specific function
variable only inside a specific function or a specific block inside the function
or a specific block inside the function then you should define it there
then you should define it there so now if we look at our main function
so now if we look at our main function you see that the code is
you see that the code is way cleaner
way cleaner we have descriptive function names that
we have descriptive function names that basically tells us what exactly is
basically tells us what exactly is happening within the main function
happening within the main function we're greeting the users then we're
we're greeting the users then we're getting their inputs we're validating
getting their inputs we're validating that input
that input and if everything is valid we're booking
and if everything is valid we're booking the ticket then getting the first names
the ticket then getting the first names and printing them
and printing them and if the remaining tickets is zero we
and if the remaining tickets is zero we just end the program
just end the program and all this logic that was basically
and all this logic that was basically crowding the main function is now
crowding the main function is now encapsulated in its own
encapsulated in its own small functions
small functions now let's actually test that everything
now let's actually test that everything still works fine
and there you go we have
we have the thank you message
the thank you message the ticket number got updated correctly
the ticket number got updated correctly and we have the first names of the
and we have the first names of the bookings printed here so everything
bookings printed here so everything works same as before now in addition to
works same as before now in addition to just cleaning things up functions have
just cleaning things up functions have another important purpose which is that
another important purpose which is that same block of code can be reused in many
same block of code can be reused in many different places in your application by
different places in your application by calling the function name
calling the function name just like variables where we define
just like variables where we define something once and reuse it hundred
something once and reuse it hundred times so for example if you were hosting
times so for example if you were hosting 10 conferences at the same time and
10 conferences at the same time and needed to ask for and validate user
needed to ask for and validate user input you can reuse that code for all 10
input you can reuse that code for all 10 conferences instead of writing that same
conferences instead of writing that same logic 10 times
now we've been working in one single file this whole time so you're maybe
file this whole time so you're maybe asking
asking what if i'm writing a more complex go
what if i'm writing a more complex go application
application with a lot of logic so do i put all the
with a lot of logic so do i put all the stuff in one go file or how does it work
stuff in one go file or how does it work can we create multiple go files that all
can we create multiple go files that all belong to the same project well remember
belong to the same project well remember at the beginning i said that go is
at the beginning i said that go is organized into packages and the package
organized into packages and the package is a collection of go files which can be
is a collection of go files which can be one file or several files and we already
one file or several files and we already have one package that we called main
have one package that we called main which we created and we also have one go
which we created and we also have one go file for that package which we called
file for that package which we called main.go
main.go now if our code got larger we can split
now if our code got larger we can split it into multiple files so for example if
it into multiple files so for example if we had 10 different conferences for
we had 10 different conferences for which users could book the tickets on
which users could book the tickets on our application
our application we could create own files for each
we could create own files for each conference booking plus if we had
conference booking plus if we had multiple files where we defined bookings
multiple files where we defined bookings for different conferences we might have
for different conferences we might have code that is shared by all these files
code that is shared by all these files so we may need the same functionality in
so we may need the same functionality in all 10
all 10 conference bookings for example we might
conference bookings for example we might need the same
need the same user input validation in all our files
user input validation in all our files so we could have a separate file
so we could have a separate file for such shared functionalities as well
for such shared functionalities as well and all these files could belong to the
and all these files could belong to the same package
same package so to demonstrate that i'm going to
so to demonstrate that i'm going to create a file here and let's call it
create a file here and let's call it helper.go
or we can also call it common or shared.go and this can
shared.go and this can include functions that are helper
include functions that are helper functions of the main application
functions of the main application again
again as an example we can take
as an example we can take user input validation
user input validation the first thing we need to define here
the first thing we need to define here is which package
is which package this go file belongs to and we have the
this go file belongs to and we have the main package that we created and we want
main package that we created and we want this file to also belong to that
this file to also belong to that main package so that's one thing we need
main package so that's one thing we need to define in each file and then we
to define in each file and then we basically just need to put some
basically just need to put some functionality here or list of functions
functionality here or list of functions that we can reference from other files
that we can reference from other files again if i had 10 different files here
again if i had 10 different files here that all share the functions right here
that all share the functions right here we can basically define them here in
we can basically define them here in helper go and then reference it from
helper go and then reference it from everywhere so i'm gonna grab validate
everywhere so i'm gonna grab validate user input function from here
and i'm going to put it into a helper dot go file so we're basically splitting
dot go file so we're basically splitting our code into multiple files
our code into multiple files of course we need to import the strings
of course we need to import the strings package here
package here because we're using it
because we're using it and if i save this
and if i save this everything is
everything is error-free
error-free in helper.go as well as
in helper.go as well as main.go so basically
main.go so basically it is super easy to divide your code up
it is super easy to divide your code up into multiple files that all belong to
into multiple files that all belong to the same package
the same package because we're referencing this validate
because we're referencing this validate user input in the main dot go file right
user input in the main dot go file right here and it knows exactly that this
here and it knows exactly that this function comes from the helper
function comes from the helper dot go file
dot go file now we want to validate that everything
now we want to validate that everything works and run our application
works and run our application however if i run my application like
however if i run my application like this
this with go run main.go and execute you see
with go run main.go and execute you see that it says validate user input is not
that it says validate user input is not defined
defined on line 21
on line 21 so right here
so right here so this function is not defined and that
so this function is not defined and that is because
is because we need to now run the application
we need to now run the application with all the files that
with all the files that belong to that application so now we
belong to that application so now we have main.go in helper dot go so we have
have main.go in helper dot go so we have to provide both files to go run command
to provide both files to go run command and now if i execute everything works
and now if i execute everything works again and
again and let's add some invalid input here
let's add some invalid input here to make sure the validate user input
to make sure the validate user input also works
and as you see we have the messages about wrong user input now of course if
about wrong user input now of course if you have tens of files here in your
you have tens of files here in your application it's not very
application it's not very convenient to have to pass them
convenient to have to pass them one by one to go run command so as an
one by one to go run command so as an alternative you can just specify a
alternative you can just specify a folder location from which you want to
folder location from which you want to execute the files so all the files in
execute the files so all the files in this folder will be executed and dot
this folder will be executed and dot specifies the current folder
specifies the current folder which is the booking app
which is the booking app so we're telling go to run
so we're telling go to run application with all the files in the
application with all the files in the current folder and again it works fine
current folder and again it works fine so that's going to be a better
so that's going to be a better alternative of course if you have
alternative of course if you have multiple files in your go project
so now we have this helper.go file that belongs to the same main package
belongs to the same main package however we could actually organize our
however we could actually organize our application code into multiple packages
application code into multiple packages so in addition to the main package we
so in addition to the main package we can have other packages that all belong
can have other packages that all belong to the application
to the application so what could be a use case for that
so what could be a use case for that let's say we have an application that
let's say we have an application that handles booking for
handles booking for 10 different conferences and the booking
10 different conferences and the booking logic for each conference is
logic for each conference is almost completely different in that case
almost completely different in that case we could actually create own packages
we could actually create own packages for each of the conference and put the
for each of the conference and put the booking logic there and plus let's say
booking logic there and plus let's say they share some common logic like
they share some common logic like validating user input and that could
validating user input and that could also be a separate package that all
also be a separate package that all other packages may share so basically
other packages may share so basically these multiple packages helps you
these multiple packages helps you organize your code and group the logic
organize your code and group the logic in a way that makes sense for your
in a way that makes sense for your application so this is a way to
application so this is a way to logically group your code so let's say
logically group your code so let's say in our example we wanted to put this
in our example we wanted to put this helper functionality in its own package
helper functionality in its own package and let's call this package also helper
and let's call this package also helper when we have multiple packages we should
when we have multiple packages we should actually create
actually create folders for them and then put all the
folders for them and then put all the files belonging to that package in that
files belonging to that package in that folder so i'm going to create a folder
folder so i'm going to create a folder called helper
called helper and put the helper.go file
and put the helper.go file in that folder again this helps organize
in that folder again this helps organize our code
our code and basically visually represent the
and basically visually represent the separation as well now of course we need
separation as well now of course we need to make a couple of adjustments
to make a couple of adjustments for our application to work again
for our application to work again the first thing is if we go to the main
the first thing is if we go to the main dot go file
dot go file right here where the function is being
right here where the function is being called you see that it says undeclared
called you see that it says undeclared names because go doesn't know this
names because go doesn't know this function anymore it doesn't know where
function anymore it doesn't know where it's coming from and that's why it says
it's coming from and that's why it says undeclared name so while this function
undeclared name so while this function was in the same package go was able to
was in the same package go was able to find it without a problem but now that
find it without a problem but now that we've moved it to another package it is
we've moved it to another package it is not
not recognized anymore in the main package
recognized anymore in the main package and remember at the very beginning i
and remember at the very beginning i said that whenever we need to use a
said that whenever we need to use a function from another package in our
function from another package in our main package we need to explicitly
main package we need to explicitly import that package and then we will be
import that package and then we will be able to use any functions inside that
able to use any functions inside that and that applies to the packages that we
and that applies to the packages that we create ourselves so the first step will
create ourselves so the first step will be to actually import
be to actually import the helper package in our main package
the helper package in our main package if we want to use any functions defined
if we want to use any functions defined inside
inside right here now the question here is can
right here now the question here is can we just import it using its name like
we just import it using its name like this helper well just writing the helper
this helper well just writing the helper the name of the package is not gonna
the name of the package is not gonna work because go will try to look for a
work because go will try to look for a helper package in one of its built-in
helper package in one of its built-in modules
modules but this is actually our own package so
but this is actually our own package so we have to explicitly tell go hey this
we have to explicitly tell go hey this is actually
is actually a package in
a package in our application or in our module so
our application or in our module so remember this go.mod file that we
remember this go.mod file that we initiated at the beginning
initiated at the beginning this
this mod file or module file actually defines
mod file or module file actually defines the name of the module which we called
the name of the module which we called booking dash app which is also
booking dash app which is also an import path for all the packages
an import path for all the packages defined in this module so if we want to
defined in this module so if we want to import a helper package inside the main
import a helper package inside the main package we have to use
package we have to use the booking app the module name before
the booking app the module name before as a path
as a path so now we are telling go
so now we are telling go import the helper package
import the helper package from our booking app module
from our booking app module and if we hover you see that it was able
and if we hover you see that it was able to find that package now we just get an
to find that package now we just get an error because we're not using it so how
error because we're not using it so how do we use a function from another
do we use a function from another package
package simply using the package name
simply using the package name dot function name just like we've been
dot function name just like we've been doing this whole time
doing this whole time so helper dot and then name of the
so helper dot and then name of the function now there is one more thing we
function now there is one more thing we need to do for this to work
need to do for this to work and right now you see that we have an
and right now you see that we have an error that says
error that says validate user input or the name of the
validate user input or the name of the function is not exported by package so
function is not exported by package so what does this mean
what does this mean whenever we want
whenever we want to create a function
to create a function in a package
in a package that can be used in another package we
that can be used in another package we have to
have to explicitly export that function so it
explicitly export that function so it can be imported in another package
can be imported in another package so exporting basically means we want to
so exporting basically means we want to make this function available for use in
make this function available for use in other
other packages and many programming languages
packages and many programming languages have this concept of exporting functions
have this concept of exporting functions to make it available
to make it available for use in other places and they all do
for use in other places and they all do it in different ways
it in different ways in go
in go the way to export a function is actually
the way to export a function is actually pretty easy
pretty easy we just
we just capitalize the name of that function
capitalize the name of that function like this and that's it
like this and that's it this simple change in the background
this simple change in the background will actually
will actually export the validate user input function
export the validate user input function so let's save it
so let's save it go back to
go back to main
main and adjust the function name here
and adjust the function name here and you see
and you see the error is gone and now
the error is gone and now we are able to use that function from
we are able to use that function from another package in our main application
another package in our main application and you probably also noticed before
and you probably also noticed before that whenever we were using a function
that whenever we were using a function from an imported package like fmt or
from an imported package like fmt or strings or whatever
strings or whatever we were using that function name with
we were using that function name with capital letter right so all the fmt
capital letter right so all the fmt package functions start with capital
package functions start with capital letter we have printf with capital p
letter we have printf with capital p print ln
print ln here we have strings.fields with capital
here we have strings.fields with capital f so that is the same concept right here
f so that is the same concept right here these are
these are functions that have been exported in
functions that have been exported in these packages and that's why we're able
these packages and that's why we're able to use them
to use them and by the way you can not only export
and by the way you can not only export functions from other packages but you
functions from other packages but you can also export
can also export variables
variables also by capitalizing
also by capitalizing the variable name so for example if all
the variable name so for example if all the conferences had the same
the conferences had the same number of tickets available you could
number of tickets available you could define that in this helper package as a
define that in this helper package as a variable
variable and then export it simply by using a
and then export it simply by using a capitalized variable name and finally we
capitalized variable name and finally we have an error here because remaining
have an error here because remaining tickets
tickets variable is not available anymore
variable is not available anymore for this function and that's again
for this function and that's again because we move this function from a
because we move this function from a main package and main package
main package and main package right here defines a package level
right here defines a package level variable called remaining tickets which
variable called remaining tickets which is only available within the package
is only available within the package main that's why it's called package
main that's why it's called package level so it's not visible to other
level so it's not visible to other packages again
packages again as i said we could export this variable
as i said we could export this variable using uppercase in the name but in our
using uppercase in the name but in our case we will just pass the variable as
case we will just pass the variable as an input parameter so let's do that
an input parameter so let's do that validate user input
validate user input and of course we have to also edit in
and of course we have to also edit in the function specification
the function specification and remaining tickets is of you int type
and remaining tickets is of you int type and
and that fixes last issue and our
that fixes last issue and our application should work again
so if i execute the application everything works fine again
everything works fine again and one more thing that i want to note
and one more thing that i want to note here is all the places we have created
here is all the places we have created variables
variables first of all we have created variables
first of all we have created variables within individual functions which made
within individual functions which made these variables available only within
these variables available only within those functions so these are basically
those functions so these are basically what's called local or function level
what's called local or function level variables
variables we also created variables that were
we also created variables that were available only within a specific block
available only within a specific block of code like right here
of code like right here so this names variable it only exists
so this names variable it only exists within this for loop
within this for loop so outside that even within the function
so outside that even within the function the variable names does not exist
the variable names does not exist so you couldn't use it outside that for
so you couldn't use it outside that for loop it's undeclared
then we saw how to define variables on a package level so that multiple functions
package level so that multiple functions can access it directly
can access it directly so we define them right here and finally
so we define them right here and finally i mentioned that if we have
i mentioned that if we have variables that we want to share across
variables that we want to share across packages
packages then we could create what's called
then we could create what's called global variable
global variable using a capitalized variable name and
using a capitalized variable name and the concept of
the concept of where we create variables and where we
where we create variables and where we can use them is called
can use them is called variable scope
variable scope okay so we have split our application
okay so we have split our application into multiple packages and as i said
into multiple packages and as i said with multiple packages you can organize
with multiple packages you can organize your code more logically
your code more logically now for the simplicity
now for the simplicity we're going to revert our example back
we're going to revert our example back to
to helper.go being in a main package and
helper.go being in a main package and continue with the rest of the demo
continue with the rest of the demo examples
examples from that state
great now we have organized our code a bit we have cleaned it up with functions
bit we have cleaned it up with functions we have divided our code into multiple
we have divided our code into multiple files and so on but there is one thing
files and so on but there is one thing we want to optimize in our application
we want to optimize in our application right now whenever user completes a
right now whenever user completes a booking we're saving only their full
booking we're saving only their full name in the bookings list
name in the bookings list but the email address and the number of
but the email address and the number of tickets they provided during the booking
tickets they provided during the booking just get ignored and thrown away we're
just get ignored and thrown away we're not saving them but we would like to
not saving them but we would like to have that information also saved for
have that information also saved for each user on the list of bookings maybe
each user on the list of bookings maybe to send them information via email in
to send them information via email in the future
the future or during the event to kind of validate
or during the event to kind of validate how many tickets they have booked
how many tickets they have booked now bookings in our case is a slice
now bookings in our case is a slice which allows us to save a list of
which allows us to save a list of string values which are the full names
string values which are the full names but instead of just a simple string
but instead of just a simple string like this
like this we want a data type
we want a data type with multiple key value pairs
with multiple key value pairs per user so something like first name
per user so something like first name [Music]
and its value last name and its value email
number of tickets so instead of a list of
so instead of a list of these type of values we want at least of
these type of values we want at least of this kind of data block for each user
this kind of data block for each user and the data type
and the data type that will allow storing multiple key
that will allow storing multiple key value pairs per user
value pairs per user is called a map
is called a map so
so a construct a data type that basically
a construct a data type that basically lets us save information about user like
lets us save information about user like this
this is provided by map and map is a common
is provided by map and map is a common data type
data type in many other programming languages as
in many other programming languages as well
well so for each user we will have a map
so for each user we will have a map with
with key names like this and their respective
key names like this and their respective values
values which of course will be different for
which of course will be different for each user
each user so let's see how we can
so let's see how we can turn our bookings list
turn our bookings list from a list of
from a list of strings to a list of
strings to a list of maps
maps first of all let's go to the book ticket
first of all let's go to the book ticket function where we're adding users first
function where we're adding users first name and last name to the bookings list
name and last name to the bookings list and right before that we're going to
and right before that we're going to create
create a map
a map for
for a user
a user and as i said map is a data type so just
and as i said map is a data type so just like with any other data type we need to
like with any other data type we need to create a variable of an empty map
create a variable of an empty map and we're going to call this
and we're going to call this let's say a user
let's say a user or user data
now how do we create a map first of all we have a keyword map
we have a keyword map and then we have to define
and then we have to define types
types for
for the key
the key and a value
and a value as i said map is a collection of key
as i said map is a collection of key value pairs
value pairs and for each one so for the
and for each one so for the for the keys which are first name last
for the keys which are first name last name email etc we have to define what
name email etc we have to define what data type they are and we also have to
data type they are and we also have to define the data types of the values
define the data types of the values and of course these two can be different
and of course these two can be different the keys in the map may be strings and
the keys in the map may be strings and the values may be integers
the values may be integers but in our case we have
but in our case we have strings for both of them
strings for both of them however this only defines the type of
however this only defines the type of the map right just like we have a type
the map right just like we have a type of
of a slice
a slice right so this is
this is a type of a slice we have a type for a map
this one right here so this is
so this is only a type what we actually need to do
only a type what we actually need to do is create an empty map
is create an empty map and we see that in the error as well it
and we see that in the error as well it says
says type definition is not an expression so
type definition is not an expression so we need an expression which is creating
we need an expression which is creating an empty map
and to create an empty map we have a built-in function called make
if i save now i only get an error that user data
now i only get an error that user data is defined but not used so that will
is defined but not used so that will give us an empty map
give us an empty map so map creation is done as a next step
so map creation is done as a next step we want to add all the user data we have
we want to add all the user data we have available to this user data map how do
available to this user data map how do we add
we add data key value pairs to a map very
data key value pairs to a map very simple actually
simple actually we have
we have name of the map and the square brackets
name of the map and the square brackets syntax that you already know from arrays
syntax that you already know from arrays and slices
and slices and inside that we have the key name
and inside that we have the key name which is first name
which is first name and the value to that which is
and the value to that which is the value of the first name variable
the value of the first name variable so that's the first key value pair that
so that's the first key value pair that we're saving into user data map
let's save another key value pair which is last
another key value pair which is last name and again
name and again value will be
value will be a last name variable which
a last name variable which we get from the user input
and we have the email which also comes from
which also comes from variable called email
variable called email so now we have added three key value
so now we have added three key value pairs to user data map so the key names
pairs to user data map so the key names are strings as we defined here and the
are strings as we defined here and the values are also strings as we defined
values are also strings as we defined here and note that you can call these
here and note that you can call these key names whatever you want so this
key names whatever you want so this could be a b c
could be a b c it doesn't really matter right but of
it doesn't really matter right but of course you want to have some descriptive
course you want to have some descriptive names which tells you what this key
names which tells you what this key actually refers to okay now the fourth
actually refers to okay now the fourth data we have is
data we have is number of tickets but the user tickets
number of tickets but the user tickets value is a uint it's not a string
value is a uint it's not a string right so the value type
right so the value type is not a string and in go specifically
is not a string and in go specifically as we saw here map can only have the
as we saw here map can only have the same data type as keys and the same data
same data type as keys and the same data type for values so we cannot
type for values so we cannot mix different data types as values
mix different data types as values again specific to go because in many
again specific to go because in many programming languages you can actually
programming languages you can actually have mixed data types in a map
have mixed data types in a map just like in a slice where we also have
just like in a slice where we also have to have just one data type which is
to have just one data type which is again specific for go because in many
again specific for go because in many other programming languages you can
other programming languages you can actually have
actually have mixed data types
mixed data types so what do we do here how do we add the
so what do we do here how do we add the user tickets value
user tickets value in our user data map well an easy way to
in our user data map well an easy way to handle this
handle this is to convert
is to convert the user ticket's view integer to a
the user ticket's view integer to a number character
number character so basically
so basically if
if user bought 30 tickets instead of 30
user bought 30 tickets instead of 30 like this we're gonna have three zero as
like this we're gonna have three zero as characters
characters and that will make it a string
and that will make it a string and this type of conversion there is a
and this type of conversion there is a built-in function in go called format
built-in function in go called format uiint
and this function comes from a package called string
a package called string convert or
convert or scr conf
scr conf stands for string conversion
stands for string conversion and this package basically includes
and this package basically includes different functions for converting
different functions for converting strings to and from other data types and
strings to and from other data types and one of them is converting uint to string
one of them is converting uint to string so of course we need to pass in our
so of course we need to pass in our uiint value
uiint value so that it can be converted to a string
so that it can be converted to a string and we do that by
and we do that by using another built-in function called
using another built-in function called uint64 which is
for a uint 64 data type
a uint 64 data type so that's the value we're converting to
so that's the value we're converting to a string
a string like this and then we have
like this and then we have to pass another input parameter here
to pass another input parameter here which stands for
which stands for decimal number
decimal number base 10. so
base 10. so now you don't need to understand every
now you don't need to understand every part of this
part of this conversion but shortly explained format
conversion but shortly explained format unit function takes our u int value
unit function takes our u int value which may be
which may be anything 1 to 50
anything 1 to 50 and formats it to a string as a decimal
and formats it to a string as a decimal number and 10 is for base 10 which
number and 10 is for base 10 which represents decimal numbers so another
represents decimal numbers so another example would be
example would be 16 for example that represents
16 for example that represents hexadecimal numbers so that's what's
hexadecimal numbers so that's what's going on here
going on here again no need to go into details here
again no need to go into details here because usually if you need these type
because usually if you need these type of conversions in your code you would
of conversions in your code you would either check out the official
either check out the official documentation of go or you will just
documentation of go or you will just google it and see the example code for
google it and see the example code for that so you don't have to memorize this
that so you don't have to memorize this kind of conversions
kind of conversions so as a result this will actually give
so as a result this will actually give us
us our user tickets in string format and we
our user tickets in string format and we can then save it
into our map and this is going to be
and this is going to be a key name for that which we can
a key name for that which we can name whatever we want i'm going to call
name whatever we want i'm going to call it number of
it number of tickets
tickets and that is going to equal
and that is going to equal to this and of course we shouldn't
to this and of course we shouldn't forget to import the string conversion
forget to import the string conversion package
package like this
like this and
and everything looks fine cool so now we are
everything looks fine cool so now we are creating a map
creating a map for each user
for each user because this book ticket function gets
because this book ticket function gets executed every time a new user books a
executed every time a new user books a ticket so the map is getting created and
ticket so the map is getting created and all the user data gets saved into that
all the user data gets saved into that map so now we need to actually take that
map so now we need to actually take that map
map with all the user data and add it to the
with all the user data and add it to the bookings list
bookings list right now we have
right now we have a slice of strings
a slice of strings as bookings
as bookings so first we need to make bookings
so first we need to make bookings variable into a slice of maps
variable into a slice of maps so what i'm going to do is i'm going to
so what i'm going to do is i'm going to copy
copy the type of this map
and right here instead of the string type i'm going to
instead of the string type i'm going to set
set a map type so we're having a list of
a map type so we're having a list of maps and not anymore a list of strings
maps and not anymore a list of strings now this curly braces was
now this curly braces was used to create
used to create an empty list
an empty list of strings however it doesn't work
of strings however it doesn't work anymore for maps so we need to actually
anymore for maps so we need to actually create
create an empty
an empty slice of maps
slice of maps and the syntax for that is
and the syntax for that is at the beginning
at the beginning again the make function that we use to
again the make function that we use to create a map
create a map like this
like this note the comparison between the two make
note the comparison between the two make calls so here
calls so here when we created a map we have a type of
when we created a map we have a type of the map and we wrap it into make
the map and we wrap it into make function and that creates an empty map
function and that creates an empty map here we're not creating an empty map
here we're not creating an empty map we're creating an empty list of maps
we're creating an empty list of maps that's why now we have the
that's why now we have the brackets
brackets before the map
before the map and
and when i save this we're going to have an
when i save this we're going to have an error because
error because this time because it's a list we need to
this time because it's a list we need to actually define
actually define a size or initial size of this empty
a size or initial size of this empty list and because slices are dynamic this
list and because slices are dynamic this is going to be the initial size and it
is going to be the initial size and it will expand automatically as we add new
will expand automatically as we add new values which means the size the initial
values which means the size the initial size can be 1 or even 0
size can be 1 or even 0 because it will increase anyways when we
because it will increase anyways when we add new elements so with this syntax
add new elements so with this syntax we're initializing
we're initializing a list of
a list of maps
maps and finally as the last step
going back to our book ticket logic we of course
to our book ticket logic we of course want to add
want to add instead of adding first name plus last
instead of adding first name plus last name in our bookings list
name in our bookings list we want to add user data map
we want to add user data map and save
and save there you go
there you go so append stays the same because it's a
so append stays the same because it's a slice again but instead of a string
slice again but instead of a string we're adding now a map to our list
we're adding now a map to our list so now we have
so now we have a bookings list which contains all user
a bookings list which contains all user information as key value pairs
information as key value pairs we still have an error in our
we still have an error in our application which is right here where
application which is right here where we are going through the bookings list
we are going through the bookings list and grabbing the first names from each
and grabbing the first names from each element
element which is logical because
which is logical because in this code we are treating
in this code we are treating the element of the bookings list as a
the element of the bookings list as a string and not a map
string and not a map which obviously has changed so we have
which obviously has changed so we have to change the logic here as well so now
to change the logic here as well so now each booking
each booking elements or the value of this booking
elements or the value of this booking variable
variable is a map with the key value pairs for
is a map with the key value pairs for first name last name email and number of
first name last name email and number of tickets so it's actually now easier to
tickets so it's actually now easier to extract the first name from the map by
extract the first name from the map by simply
simply using the key name which we called first
using the key name which we called first name
name and that's it so this will give us a
and that's it so this will give us a value of the first name we don't have to
value of the first name we don't have to split a string or do anything here and
split a string or do anything here and we can also use that directly right here
we can also use that directly right here and save and that's it so again in our
and save and that's it so again in our bookings list
bookings list we have maps for each user with
we have maps for each user with different data one of them being first
different data one of them being first name so
name so we can grab the first name value from
we can grab the first name value from each
each map using this syntax and then edit to
map using this syntax and then edit to the first name slice so that fixes the
the first name slice so that fixes the issue and finally as a great feature of
issue and finally as a great feature of go we're reminded that we're no longer
go we're reminded that we're no longer using the strings package
using the strings package so we should get rid of it
so we should get rid of it and no more errors in our application so
and no more errors in our application so now we can
now we can run our application to make sure
run our application to make sure everything works
everything works perfectly plus to also check
perfectly plus to also check our changes
our changes that we store
that we store the complete user data in the bookings
the complete user data in the bookings let's also print out
let's also print out the bookings list of maps after every
the bookings list of maps after every booking let's see
booking let's see list of bookings
and there you go so after the booking we have a list of bookings which is
have a list of bookings which is a slice
a slice you see with the brackets and inside
you see with the brackets and inside that we have one map because we just
that we have one map because we just have one booking and this map contains
have one booking and this map contains basically these key value pairs for
basically these key value pairs for email first name last name and number of
email first name last name and number of tickets divided separated by columns and
tickets divided separated by columns and let's try another one
and now our list of bookings has two maps like this and the printing of
two maps like this and the printing of first names also works fine
now let's say we wanted to collect different types of data on users for
different types of data on users for example we asked for their date of birth
example we asked for their date of birth which is a date value type or we asked a
which is a date value type or we asked a user to opt in for a newsletter and we
user to opt in for a newsletter and we would save that information as a boolean
would save that information as a boolean data type like is opted in for
data type like is opted in for newsletter we may even want to save
newsletter we may even want to save lists associated with users like let's
lists associated with users like let's say a manager books tickets for her team
say a manager books tickets for her team and we would like to know names of these
and we would like to know names of these team members to know who will attend the
team members to know who will attend the conference so for this user we can save
conference so for this user we can save a list of team members they will bring
a list of team members they will bring with them and this would be an array or
with them and this would be an array or slice of attendance names if we wanted
slice of attendance names if we wanted the team members email addresses in
the team members email addresses in addition then this would even be a slice
addition then this would even be a slice of
of maps where each map will hold the name
maps where each map will hold the name of the attendant and their email address
of the attendant and their email address so user entity would have all these data
so user entity would have all these data of different data types associated to it
of different data types associated to it we may also have other entities in our
we may also have other entities in our application like a conference which will
application like a conference which will have its own data associated to it like
have its own data associated to it like in which cities the conference is held
in which cities the conference is held on which dates it is hosted how many
on which dates it is hosted how many people are attending etc again values of
people are attending etc again values of mixed data types and as we saw in the
mixed data types and as we saw in the previous example maps in go limit
previous example maps in go limit values to only one data type that's why
values to only one data type that's why we had to do this type conversion to
we had to do this type conversion to save number of tickets for a user as a
save number of tickets for a user as a string instead of uiint so how can we
string instead of uiint so how can we save mixed data type values for an
save mixed data type values for an entity
entity like a user or conference in our go
like a user or conference in our go application
application well for that we can use what's called a
well for that we can use what's called a struct
struct in go which stands for structure structs
in go which stands for structure structs or structures let us define key value
or structures let us define key value pairs for an entity like user but with
pairs for an entity like user but with mixed data types so let's see how we can
mixed data types so let's see how we can create a struct so right here outside
create a struct so right here outside all the functions on the package level
all the functions on the package level we're going to create a struct first of
we're going to create a struct first of all we have a keyword struct
all we have a keyword struct and it's block
and it's block with curly braces
with curly braces and within the block we define the list
and within the block we define the list of keys
of keys like first name
like first name last name
last name email
email and
and number of tickets
number of tickets like this
like this note that we're not using quotes here
note that we're not using quotes here and for each key in the struct we also
and for each key in the struct we also have to define
have to define the type of the value right so instead
the type of the value right so instead of having one type for all the values we
of having one type for all the values we can choose
can choose different type for each value so the
different type for each value so the first name will be a string the last
first name will be a string the last name will be a string email will be a
name will be a string email will be a string and number of tickets will be you
string and number of tickets will be you int
int again if we had other data types like a
again if we had other data types like a boolean for
boolean for is user opted in
is user opted in for
for news
news letter
letter we can basically add them right so we
we can basically add them right so we can have mixed data types for the values
can have mixed data types for the values but our struct is not done yet first we
but our struct is not done yet first we need a name for our struct
need a name for our struct which in our case
which in our case can be a user data for example and
can be a user data for example and finally
finally at the beginning we have to
at the beginning we have to create a struct using type keyword like
create a struct using type keyword like this
this this actually means that we're creating
this actually means that we're creating a custom type in our application which
a custom type in our application which is called user data
is called user data another very important advantage of
another very important advantage of structures over maps is that in addition
structures over maps is that in addition to
to just being able to specify these mixed
just being able to specify these mixed data types
data types the structure gives us this custom type
the structure gives us this custom type like user where we can define exactly
like user where we can define exactly what user
what user type should look like so what properties
type should look like so what properties it should have and with map we just have
it should have and with map we just have an empty list where we can just put
an empty list where we can just put whatever we want so structure allows you
whatever we want so structure allows you to create a predefined
to create a predefined structure
structure by listing all the properties that it
by listing all the properties that it should have so here we are defining the
should have so here we are defining the structure of our user type and that a
structure of our user type and that a user
user has first name last name email and
has first name last name email and number of tickets
number of tickets and if you know object oriented
and if you know object oriented languages like java struct can be
languages like java struct can be compared to classes in those languages
compared to classes in those languages so we're creating a custom data type
so we're creating a custom data type called user data with these properties
called user data with these properties associated to it great so now let's go
associated to it great so now let's go ahead and use our user data structure
ahead and use our user data structure instead of the map so first of all we're
instead of the map so first of all we're going to change
going to change our bookings from a list of
our bookings from a list of maps to a list of user data structures
maps to a list of user data structures so we're going to grab the map type and
so we're going to grab the map type and we're going to replace it with user data
we're going to replace it with user data struct type like this
struct type like this nicer syntax
nicer syntax everything else stays the same so this
everything else stays the same so this line basically now creates or initiates
line basically now creates or initiates an empty list of user data structs
an empty list of user data structs now of course
now of course we also have to create the user data
we also have to create the user data struct instead of the map in the book
struct instead of the map in the book ticket function
ticket function so let's scroll down to here and the
so let's scroll down to here and the user data instead of creating a map here
user data instead of creating a map here we're
we're going to create
going to create a struct
a struct like this the name of the struct
like this the name of the struct and curly braces
and curly braces and inside that we are going to set the
and inside that we are going to set the values
values for each property or each field name so
for each property or each field name so first name is going to be the name from
first name is going to be the name from the first name variable in this case
the first name variable in this case they're called the same but of course
they're called the same but of course could be different values
could be different values then we have the last name
then we have the last name field of our struct
and the value will be from the last name variable
variable email
email same here
same here and
and the key name for user tickets
the key name for user tickets like this and the value called user
like this and the value called user tickets
tickets and when setting these values we have to
and when setting these values we have to separate each line using a comma so at
separate each line using a comma so at the end of each
the end of each line
line so this will give us a user data object
so this will give us a user data object with all the user data so we don't
with all the user data so we don't actually need any conversion from
actually need any conversion from you in type to string as well as we
you in type to string as well as we don't need these
don't need these lines here so let's get rid of it and
lines here so let's get rid of it and again our code looks a little bit more
again our code looks a little bit more cleaner
cleaner and a reminder from go
and a reminder from go that we don't need the string conversion
that we don't need the string conversion package anymore so let's
package anymore so let's remove that as well and finally as the
remove that as well and finally as the last fix because we still have one issue
which is right here getting the first names because now we are accessing the
names because now we are accessing the first name
first name with a syntax for map
with a syntax for map but a booking
but a booking variable is not a map anymore it's a
variable is not a map anymore it's a struct and to get values from struct
struct and to get values from struct basically we use a syntax with dot and
basically we use a syntax with dot and as i mentioned a big difference of
as i mentioned a big difference of structures of our maps is that it gives
structures of our maps is that it gives you a predefined structure so now when i
you a predefined structure so now when i type dot after
type dot after a struct element
a struct element go actually gives me suggestions
go actually gives me suggestions property names that destruct has and i
property names that destruct has and i can just choose one like this but also
can just choose one like this but also if i actually misspell a name of the
if i actually misspell a name of the property of a struct go can help me
property of a struct go can help me identify this error even before running
identify this error even before running the application
the application and this is because we have created a
and this is because we have created a real type with a structure in which the
real type with a structure in which the go compiler knows the associated
go compiler knows the associated properties so as you see when working
properties so as you see when working with structs the syntax is simpler than
with structs the syntax is simpler than with maps so our code looks cleaner
with maps so our code looks cleaner and less messy awesome so that's
and less messy awesome so that's basically the final result of our code
basically the final result of our code we're also using just one package here
we're also using just one package here so we can
so we can remove the parentheses here and again we
remove the parentheses here and again we can
can test
test our application
and in the output you see the line where we're printing the list
the line where we're printing the list of bookings which is now a list of
of bookings which is now a list of structs this is how it looks like so we
structs this is how it looks like so we have a slice with square brackets and
have a slice with square brackets and inside that we have
inside that we have one element
one element which is a struct with a nice
which is a struct with a nice short output and again if we add another
short output and again if we add another user booking
user booking like this you see one struct
like this you see one struct and another one
now let's say after user books at ticket we want to generate
we want to generate that book ticket and send it to the user
that book ticket and send it to the user per email address that they entered
so let's create a function called send ticket
ticket that generates a ticket
that generates a ticket and then sends it per email and we're
and then sends it per email and we're just going to simulate this logic with a
just going to simulate this logic with a simple code and to simulate generating a
simple code and to simulate generating a ticket we're just going to put together
ticket we're just going to put together a string that basically says this is a
a string that basically says this is a ticket for a certain user
so let's use a printf so we're just printing it out
printing it out and let's say this many
and let's say this many tickets
tickets for
for first name
first name last name
last name of the user and let's
add them here if i save this
if i save this of course we need to
of course we need to pass those
pass those variables as input parameters right so
variables as input parameters right so we can use them in a function so i'm
we can use them in a function so i'm going to define them all here
going to define them all here i'm actually just going to copy this
i'm actually just going to copy this and then just add
and then just add types so we have
types so we have uint
uint string
string and another string
and another string like this
like this now let's say instead of just printing
now let's say instead of just printing out this
out this string we wanted to save it into a
string we wanted to save it into a variable called ticket that we would
variable called ticket that we would then send per email and that may be
then send per email and that may be another useful example that you may need
another useful example that you may need in your applications to basically
in your applications to basically save formatted strings in a variable
save formatted strings in a variable instead of just printing them out now if
instead of just printing them out now if i do variable ticket here and save it
i do variable ticket here and save it you see that
you see that i get an error because this doesn't give
i get an error because this doesn't give me the formatted string back it just
me the formatted string back it just prints it out to the console and it
prints it out to the console and it doesn't return string for that we
doesn't return string for that we actually have a different function from
actually have a different function from the format package which is called
the format package which is called s print
s print f and if i save this you see that now we
f and if i save this you see that now we just get an error because ticket is
just get an error because ticket is declared but not used so this function
declared but not used so this function basically helps you put together a
basically helps you put together a string just like in the formatted output
string just like in the formatted output here
here but instead of printing it out you can
but instead of printing it out you can save it into a string variable so we
save it into a string variable so we have simulated the tick generation
have simulated the tick generation and now let's simulate sending it per
and now let's simulate sending it per email in this case we're just going to
email in this case we're just going to use a print statement
use a print statement which says
which says sending
sending ticket
and this is the ticket to
to email address
email address and that's an email address
and that's an email address so we have the ticket
so we have the ticket so here we substitute the ticket itself
so here we substitute the ticket itself so this string that we put here together
so this string that we put here together and the email address
and the email address and now we have to add email address
and now we have to add email address also
also as
as input parameter
input parameter so we can use it here and let's do a
so we can use it here and let's do a little bit more formatting so we can see
little bit more formatting so we can see the ticket part really well so i'm just
the ticket part really well so i'm just going to do column here
going to do column here and let's print the ticket on a new line
and let's print the ticket on a new line like this
like this let's put a new line here as well
let's put a new line here as well and i'm also gonna add some visual
and i'm also gonna add some visual divider for the ticket sending logic
divider for the ticket sending logic before sending the ticket
and afterwards and that's just going to be
afterwards and that's just going to be simple visual divider something that
simple visual divider something that we're just going to notice immediately
we're just going to notice immediately like this
like this println there you go so this basically
println there you go so this basically just simulates with simple code a logic
just simulates with simple code a logic for generating a ticket and
for generating a ticket and then sending it to email after user
then sending it to email after user booked the ticket so i'm going to take
booked the ticket so i'm going to take the name of the function and we actually
the name of the function and we actually have to call this right so in the main
have to call this right so in the main function right after book ticket gets
function right after book ticket gets executed we're going to
executed we're going to call send ticket and this expects
call send ticket and this expects the variables
the variables which are actually the same as here
which are actually the same as here right so we have user tickets first name
right so we have user tickets first name last name email
last name email just like we defined it here
just like we defined it here awesome so
awesome so our application is ready let's now
our application is ready let's now actually run our application
actually run our application and see that this output gets printed
and see that this output gets printed out
and there you go so we have 45 tickets remaining which is in the
45 tickets remaining which is in the book ticket function and then send
book ticket function and then send ticket gets executed it starts right
ticket gets executed it starts right here and we are saying sending tickets
here and we are saying sending tickets this is the string we put together how
this is the string we put together how many tickets the user bought and the
many tickets the user bought and the username last name to email address
username last name to email address they gave us awesome everything works
they gave us awesome everything works fine now let's say
fine now let's say that generating
that generating the ticket and then sending it per email
the ticket and then sending it per email actually takes some time it's not a fast
actually takes some time it's not a fast process that we
process that we simulated here some data needs to be
simulated here some data needs to be processed in the background so if we had
processed in the background so if we had a real code that really generates a pdf
a real code that really generates a pdf of a ticket and then sends it using an
of a ticket and then sends it using an email client to an email address it
email client to an email address it would actually take some time right it
would actually take some time right it would not be this fast so let's say it
would not be this fast so let's say it would take 10 seconds and we're also
would take 10 seconds and we're also going to simulate this 10 second delay
going to simulate this 10 second delay using a function called
using a function called sleep
sleep from a time package
from a time package and in a slip function we're going to
and in a slip function we're going to say how long it needs to sleep so 10
say how long it needs to sleep so 10 seconds
again the second unit is in the time package and we of course have to
package and we of course have to import it
and there you go so now whenever this function gets
so now whenever this function gets called we're simulating that something
called we're simulating that something happens here for 10 seconds so
happens here for 10 seconds so in this case it's just sleeping and
in this case it's just sleeping and after 10 seconds
after 10 seconds this code gets executed and we're going
this code gets executed and we're going to get the summary so the sleep
to get the summary so the sleep basically just stops the execution of
basically just stops the execution of the thread for 10 seconds that's what
the thread for 10 seconds that's what we're doing
we're doing so now
so now with this change
with this change let's run the application now and see
let's run the application now and see what happens or see how
what happens or see how application can handle this kind of time
application can handle this kind of time delay
so i'm going to clean this up let's run input the data
and as you see i didn't get an input enter your last name and if i type
enter your last name and if i type something here
something here the application basically is blocked and
the application basically is blocked and now you see
now you see that after 10 seconds
that after 10 seconds were over
were over this got printed out and now application
this got printed out and now application became responsive again and now it's
became responsive again and now it's asking me for
asking me for inputs for another user right
inputs for another user right let's do that again
and again you see it's stopped here
it's stopped here and now whatever i input
and now whatever i input i don't get a feedback from the
i don't get a feedback from the application i just have to wait until
application i just have to wait until this here gets printed out or this gets
this here gets printed out or this gets completed
so the application is being blocked while this code gets executed and once
while this code gets executed and once it's done
it's done then we can continue to another booking
then we can continue to another booking now if this was an application that
now if this was an application that should handle multiple bookings of
should handle multiple bookings of multiple users then this would not be an
multiple users then this would not be an optimal performance right and that's why
optimal performance right and that's why we need concurrency in applications and
we need concurrency in applications and as i mentioned at the beginning the main
as i mentioned at the beginning the main advantage of goal programming language
advantage of goal programming language is the simplicity of coding concurrent
is the simplicity of coding concurrent applications so we can make our
applications so we can make our application concurrent in a very easy
application concurrent in a very easy way
way in go
in go compared to other languages
compared to other languages so what would concurrency mean in this
so what would concurrency mean in this case
case well our application runs in a single
well our application runs in a single thread
thread right when go starts executing this main
right when go starts executing this main function
function everything that you see here will be
everything that you see here will be executed from start to finish in a
executed from start to finish in a single thread which means all code lines
single thread which means all code lines get executed one by one in this order in
get executed one by one in this order in our single threaded application
our single threaded application and that means if one of the lines
and that means if one of the lines like this one here
like this one here takes longer
takes longer the execution in this thread
the execution in this thread is blocked so the next line gets
is blocked so the next line gets executed only after this one is done
executed only after this one is done doing its job so this has to wait those
doing its job so this has to wait those 10 seconds
10 seconds until it gets executed but to optimize
until it gets executed but to optimize this instead of
this instead of just waiting
just waiting for a certain code line to finish when
for a certain code line to finish when we know that something takes longer
we know that something takes longer we want to start a separate thread for
we want to start a separate thread for it and execute
it and execute this logic in a separate thread so break
this logic in a separate thread so break out of the main thread
out of the main thread and do this in its own separate thread
and do this in its own separate thread so now instead of waiting for 10 seconds
so now instead of waiting for 10 seconds to run the next line after the function
to run the next line after the function the application executes it gets to this
the application executes it gets to this point it spins off a new thread pushes
point it spins off a new thread pushes the code execution there and it
the code execution there and it immediately continues to the next line
immediately continues to the next line so there's no waiting or blocking here
so there's no waiting or blocking here very simple concept actually and that
very simple concept actually and that would mean in our application
would mean in our application that while the ticket is being generated
that while the ticket is being generated and sent to the user who just booked the
and sent to the user who just booked the ticket we can continue to the next
ticket we can continue to the next booking for the next user without any
booking for the next user without any interruption when the second user is
interruption when the second user is also done
also done booking her ticket
booking her ticket then again the iteration will come here
then again the iteration will come here and again it will spin off a new thread
and again it will spin off a new thread to generate the second user's ticket and
to generate the second user's ticket and send it per email and so on so basically
send it per email and so on so basically if 20 users book the ticket at the same
if 20 users book the ticket at the same time 20 new threads will be created each
time 20 new threads will be created each one will do its job and once completed
one will do its job and once completed the thread will be deleted and this
the thread will be deleted and this whole time the main application flow
whole time the main application flow will continue without any interruptions
will continue without any interruptions all right now that sounds all cool but
all right now that sounds all cool but how do we create those threads and make
how do we create those threads and make the code in this function so the
the code in this function so the centicade function
centicade function run in that separate thread how do we do
run in that separate thread how do we do that
that well we just write go in front of it
well we just write go in front of it and that's it
and that's it we just made our application concurrent
we just made our application concurrent with a simple go keyword and this
with a simple go keyword and this keyword basically
keyword basically abstracts away the whole thread creation
abstracts away the whole thread creation and cleanup and all these
and cleanup and all these for you so you as a developer don't have
for you so you as a developer don't have to worry about this
to worry about this so now let's actually go and test it i'm
so now let's actually go and test it i'm going to save it
going to save it clean up
clean up and
and input our data
and now when i click enter i should be immediately
i should be immediately prompted for another user's booking so
prompted for another user's booking so enter and there you go it asks me again
enter and there you go it asks me again for enter your first name so let's
for enter your first name so let's continue
and while i'm actually typing
typing we see that at some point the ticket
we see that at some point the ticket creation logic was completed and i see
creation logic was completed and i see the output here so even though it
the output here so even though it printed out
printed out the text in the middle of my user input
the text in the middle of my user input it doesn't actually interrupt the
it doesn't actually interrupt the application flow so here i have
application flow so here i have dot com
dot com and then continue with user tickets
and then continue with user tickets and again i can go on to the next user
and again i can go on to the next user booking
and again at some point the second ticket is done and it gets printed here
ticket is done and it gets printed here and the user would be able to basically
and the user would be able to basically continue their booking without problems
continue their booking without problems so as you see everything works great and
so as you see everything works great and we have improved the performance of our
we have improved the performance of our application with a simple change in our
application with a simple change in our code and this means now
code and this means now even if the ticket generation took five
even if the ticket generation took five times longer or ten times longer the
times longer or ten times longer the main application flow would be
main application flow would be unaffected by that and the users will
unaffected by that and the users will basically get their tickets per email a
basically get their tickets per email a little later which is also not an issue
little later which is also not an issue and to demonstrate that i'm gonna
and to demonstrate that i'm gonna actually put that timer to 50 seconds
actually put that timer to 50 seconds instead of 10
instead of 10 and let's execute again
so basically i have simulated booking for three different users the ticket for
for three different users the ticket for the first user is not done yet
the first user is not done yet but we can keep booking new tickets
but we can keep booking new tickets and at some point
and at some point after the 50 seconds are over you see
after the 50 seconds are over you see the output for the first user and the
the output for the first user and the second user
and finally for
for the third user so our application stays
the third user so our application stays responsive no matter how long this code
responsive no matter how long this code actually takes to execute
now let's see one more thing about concurrency in our applications
concurrency in our applications let's say we did not have a for loop
let's say we did not have a for loop here that keeps on asking for the new
here that keeps on asking for the new booking which means once the booking is
booking which means once the booking is done the main application would exit
done the main application would exit there is no
there is no next iteration here so i'm going to
next iteration here so i'm going to remove this for loop
we don't need a break statement because there is no loop
there is no loop so basically our application only allows
so basically our application only allows for one booking so let's run our
for one booking so let's run our application and see what happens with
application and see what happens with the booking logic
so we entered our data the summary
the summary got printed out
got printed out thank you message how many tickets are
thank you message how many tickets are left and the first names
left and the first names but there is no
but there is no ticket generation
ticket generation output here so
output here so all the code in here send ticket
all the code in here send ticket that prints out
that prints out this three lines we don't see them in
this three lines we don't see them in the output because they never got
the output because they never got executed
executed so the application exited before this
so the application exited before this function was done and this means that
function was done and this means that the main thread does not wait for any
the main thread does not wait for any additional threads to complete or even
additional threads to complete or even start when the main thread is done the
start when the main thread is done the application is done as well so whatever
application is done as well so whatever is happening in the other threads are
is happening in the other threads are basically getting terminated and ignored
basically getting terminated and ignored so how can we fix this because obviously
so how can we fix this because obviously we want to send
we want to send the user their ticket right well for
the user their ticket right well for that we need to tell the main thread
that we need to tell the main thread that it needs to wait until this thread
that it needs to wait until this thread is done doing its job and for that first
is done doing its job and for that first we need to create what's called a weight
we need to create what's called a weight group so outside the main function right
group so outside the main function right here we're going to create a weight
here we're going to create a weight group
group with curly braces
with curly braces and this comes from a sync package and
and this comes from a sync package and we can then save the result into a
we can then save the result into a variable called
variable called wg or weight group
wg or weight group and
and of course we need to import the sync
of course we need to import the sync package
package and there you go
and there you go and weight group
and weight group has three functions which we can call
has three functions which we can call using this variable so on wg right
using this variable so on wg right before we spin off
before we spin off a new thread
a new thread we're going to call the first function
we're going to call the first function which is called ed
which is called ed and this function adds a number of
and this function adds a number of threads that the main thread should wait
threads that the main thread should wait for and should be executed before
for and should be executed before creating a new thread and in our case we
creating a new thread and in our case we have one new thread that we are adding
have one new thread that we are adding so
so we're gonna put one here so if you had
we're gonna put one here so if you had another
another go
go do something else function here
do something else function here then you would put two
another function that we have the second function of weight group is
the second function of weight group is called weight
called weight and it needs to be executed at the end
and it needs to be executed at the end of
of the main thread so as a last line of the
the main thread so as a last line of the code we're going to do weight and this
code we're going to do weight and this basically waits for all the threads that
basically waits for all the threads that were added right here to be done doing
were added right here to be done doing its job before the application can exit
its job before the application can exit so this just waits
so this just waits until this one is done
until this one is done and the third function
and the third function is called done which gets executed in
is called done which gets executed in the function that runs in a separate
the function that runs in a separate thread so incenticate
thread so incenticate and at the end of the logic when
and at the end of the logic when everything is done we're going to call
everything is done we're going to call weight group
weight group done
done so
so done function removes the thread
that we added right here from the waiting list
waiting list it's basically saying to the weight
it's basically saying to the weight group i'm done executing so the main
group i'm done executing so the main thread doesn't have to wait for me
thread doesn't have to wait for me anymore so the add function is
anymore so the add function is increasing the counter
increasing the counter of
of threads that the application should wait
threads that the application should wait for and done is decreasing that counter
for and done is decreasing that counter so when the counter is zero which means
so when the counter is zero which means the main thread has no threads to wait
the main thread has no threads to wait for it can exit the application so this
for it can exit the application so this doesn't have to wait anymore so now with
doesn't have to wait anymore so now with these code changes
these code changes let's run our application again and we
let's run our application again and we should see the ticket being printed out
should see the ticket being printed out before the application exits
so the summary got already printed out now it's just waiting
now it's just waiting as you see it's not exiting it is
as you see it's not exiting it is basically waiting for those
basically waiting for those 50 seconds to be over and then
50 seconds to be over and then we'll execute these lines of code and
we'll execute these lines of code and you see the output of sent ticket so
you see the output of sent ticket so this time the application actually
this time the application actually waited for this separate thread to be
waited for this separate thread to be done executing its logic and once this
done executing its logic and once this was printed out as you see the
was printed out as you see the application exited now you may be
application exited now you may be thinking you can surely implement
thinking you can surely implement concurrency in other languages like java
concurrency in other languages like java right which is true but in other
right which is true but in other languages that support concurrency we
languages that support concurrency we have two differences with go first of
have two differences with go first of all
all writing code for concurrency
writing code for concurrency in those languages is way more complex
in those languages is way more complex and you have more overhead for the
and you have more overhead for the initial configuration and second
initial configuration and second creating threads is more expensive which
creating threads is more expensive which means it takes longer to spin off a new
means it takes longer to spin off a new thread and it also needs more memory
thread and it also needs more memory space allocated to it now what is the
space allocated to it now what is the reason for these differences or what
reason for these differences or what does go actually do better or more
does go actually do better or more efficiently well in go when we create a
efficiently well in go when we create a thread go actually spins off what's
thread go actually spins off what's called a green thread green thread in go
called a green thread green thread in go is an abstraction of an actual thread
is an abstraction of an actual thread which is an operating system thread and
which is an operating system thread and it's called a go routine so with gold
it's called a go routine so with gold keyword we're actually creating go
keyword we're actually creating go routines so in go we are only
routines so in go we are only interacting with these high level goal
interacting with these high level goal routines instead of the low-level
routines instead of the low-level operating system threats and an
operating system threats and an advantage of working with this threat
advantage of working with this threat abstraction is that first of all it's
abstraction is that first of all it's cheaper to create it's more lightweight
cheaper to create it's more lightweight and takes
and takes little memory space so each time you
little memory space so each time you create a thread you actually have way
create a thread you actually have way less overhead
less overhead and that means you can easily create and
and that means you can easily create and use thousands or tens of thousands of
use thousands or tens of thousands of threads pretty fast which in other
threads pretty fast which in other languages is normally not possible
languages is normally not possible without affecting the application
without affecting the application performance so in comparison other
performance so in comparison other programming languages like java that i
programming languages like java that i mentioned use operating system threads
mentioned use operating system threads which again need more memory space more
which again need more memory space more time to create and that's why in these
time to create and that's why in these languages sometimes we have concepts
languages sometimes we have concepts like thread pooling to optimize working
like thread pooling to optimize working with threats
with threats and one last difference is that in other
and one last difference is that in other programming languages
programming languages threats do not have an easy
threats do not have an easy communication medium or way to talk to
communication medium or way to talk to each other in contrast
each other in contrast go routines has a concept of channels
go routines has a concept of channels which is a built-in functionality which
which is a built-in functionality which allows
allows easy and safe communication between the
easy and safe communication between the go routines
go routines and this is a functionality that helps
and this is a functionality that helps you handle
you handle concurrency issues which are issues that
concurrency issues which are issues that may occur when threats have shared data
may occur when threats have shared data or are dependent on each other now we're
or are dependent on each other now we're not covering this in this beginner
not covering this in this beginner tutorial because it's a more advanced
tutorial because it's a more advanced topic but it's an important one so i
topic but it's an important one so i will include it in my upcoming go course
will include it in my upcoming go course congratulations you made it till the end
congratulations you made it till the end so what do you think about go have you
so what do you think about go have you already used it in one of your projects
already used it in one of your projects share your thoughts in the comments
share your thoughts in the comments section of the video now in this
section of the video now in this beginner course we built a simple cli
beginner course we built a simple cli application without persistence but
application without persistence but learned a lot of
learned a lot of the main goal concepts but of course in
the main goal concepts but of course in real life this would be a web
real life this would be a web application with a ui and a database
application with a ui and a database connected to it where multiple users can
connected to it where multiple users can book their tickets at the same time and
book their tickets at the same time and the bookings will be persisted in a
the bookings will be persisted in a database so if you want to take your go
database so if you want to take your go skills to another level and want to
skills to another level and want to learn more advanced concepts in go i'm
learn more advanced concepts in go i'm actually going to create a go course
actually going to create a go course where you will learn to build exactly
where you will learn to build exactly this kind of application with go
this kind of application with go if you want to be notified when the
if you want to be notified when the course is out then check out the video
course is out then check out the video description for a sign up link or if
description for a sign up link or if you're watching this video by the time
you're watching this video by the time the course is already released then you
the course is already released then you will find a link to the course itself
will find a link to the course itself and with that thank you for watching and
and with that thank you for watching and see you in the next video
Click on any text or timestamp to jump to that moment in the video
Share:
Most transcripts ready in under 5 seconds
One-Click Copy125+ LanguagesSearch ContentJump to Timestamps
Paste YouTube URL
Enter any YouTube video link to get the full transcript
Transcript Extraction Form
Most transcripts ready in under 5 seconds
Get Our Chrome Extension
Get transcripts instantly without leaving YouTube. Install our Chrome extension for one-click access to any video's transcript directly on the watch page.