Go (Golang) Tutorial #9 - Using Functions
Summary
TLDRThis script introduces the concept of functions in Go, a popular programming language. It explains the main function and how to create custom functions, including those with parameters and return values. The video demonstrates how to reuse code effectively by defining and calling functions like 'greeting' and 'bye', as well as more complex examples involving slices and functions as arguments. The script also covers formatting output for better readability, showcasing the versatility and utility of functions in Go for various programming tasks.
Takeaways
- π Functions in Go are a way to organize and reuse code, improving efficiency and maintainability.
- π The main function in Go executes automatically when the program runs, serving as the entry point for the application.
- π Functions can be defined outside of the main function, allowing them to be used in the main function and potentially in other files.
- π― Functions can take parameters, which are specified in the function declaration, ensuring type safety and functionality.
- π Functions can perform actions such as printing to the console, as demonstrated with the greeting and bye functions.
- π Functions can be called multiple times with different arguments, showcasing the reusability of functions in Go.
- π Functions can accept multiple arguments, enabling complex operations with various inputs.
- π Functions can also take other functions as arguments, allowing for dynamic and flexible behavior.
- π The concept of 'range' and slices is used to iterate over collections, which can be utilized inside functions.
- π Returning values from functions is a key feature, allowing the results of computations to be used elsewhere in the code.
- π Functions can return values of any type, and the return type must be specified in the function signature.
- π¨ Formatting output, such as limiting decimal places, can be achieved using formatted strings (e.g., printf).
Q & A
What is the main purpose of functions in Go programming language?
-The main purpose of functions in Go is to organize and reuse code effectively. Functions allow developers to create reusable blocks of code that can be called upon as needed, promoting modularity and code maintainability.
How does the main function in Go behave?
-The main function in Go is the entry point of the program. It is the first function that gets executed when the program runs, and it does not require an explicit call to start. It is marked with the 'func' keyword followed by 'main' and a parameter list that includes 'int' and 'string'.
How can you define a function in Go outside of the main function?
-You can define a function outside of the main function by using the 'func' keyword, followed by the function name, parameter list (if any), and a block of code enclosed in curly braces. The function can then be called from within the main function or other parts of the code.
What is the purpose of parameters in a function?
-Parameters in a function serve as inputs that allow the function to accept data from the caller. They enable the function to be flexible and dynamic, as it can operate on different data each time it is called, enhancing its reusability.
How do you pass a variable to a function in Go?
-In Go, you pass a variable to a function by specifying the variable's name within the argument list when calling the function. The variable's value is then passed to the function, allowing it to be used within the function's body.
What is the significance of the 'fmt.Println' and 'printf' in the context of the script?
-'fmt.Println' and 'printf' are standard Go packages used for printing output to the console. 'fmt.Println' prints the given arguments and a newline character, while 'printf' allows for formatted string output, which can include variables as part of the output using the '%v' verb.
How can you reuse code with functions in Go?
-You can reuse code in Go by defining functions that perform specific tasks and then calling these functions whenever those tasks need to be executed. This practice reduces redundancy and makes the code more efficient and easier to maintain.
What is a slice in Go and how is it used in the context of the script?
-A slice in Go is a dynamic array that holds a reference to an array and provides a way to access elements of the array. In the script, a slice of strings is used as an argument in a function to demonstrate how multiple elements can be iterated over and processed by a function.
How do you pass a function as an argument to another function in Go?
-In Go, you can pass a function as an argument to another function by specifying the type 'func' in the parameter list of the receiving function. The function being passed must match the expected signature (i.e., the number and types of parameters) of the function argument in the receiving function.
What is the purpose of the 'range' keyword in a for loop when iterating over a slice?
-The 'range' keyword in a for loop is used to iterate over the elements of a slice without needing the index. It automatically assigns the current element to a variable (denoted by the underscore '_' if the index is not needed) and loops through the entire slice.
How do you return a value from a function in Go?
-In Go, you return a value from a function using the 'return' keyword followed by the value you wish to return. The function's signature must specify the return type, and the type of the value being returned must match the declared return type.
How can you format the output of a float in Go?
-In Go, you can format the output of a float using the 'fmt.Printf' function with a formatted string that includes the '%f' verb followed by a precision specifier (e.g., '%.2f' for two decimal places). This allows you to control the appearance of the floating-point number when it is printed to the console.
Outlines
π Introduction to Functions in Go
This paragraph introduces the concept of functions in the Go programming language. It explains the use of the main function that automatically executes when a file is run, and how additional functions can be created and used within the main function or across other files. The video demonstrates how to define a function called 'sayGreeting' that takes a string parameter 'n', which represents a name, and prints a greeting message using that name. Another function 'sayBye' is also created with similar functionality. The importance of functions for code reusability is emphasized, and an example is given of how to call these functions within the main function, passing names as arguments to produce personalized greetings.
π Using Functions with Multiple Arguments and Returning Values
This paragraph delves into the use of functions with multiple arguments and the concept of returning values from functions. A new function 'cycleNames' is introduced, which takes a slice of strings and a function as arguments. The video shows how to iterate over a slice using a for loop and how to call a function for each element in the slice. Another function 'sayGreeting' is used as an example of a function passed as an argument. The concept of returning values from functions is explained through the creation of a 'circleArea' function that calculates the area of a circle given its radius. The function returns a float64 value, and the video demonstrates how to store and print this value with formatted output for better readability.
π― Wrapping Up Function Concepts in Go
In this final paragraph, the video wraps up the discussion on functions in Go by summarizing the key points covered. The focus is on the ability to create reusable functions to reduce code redundancy and improve maintainability. The video reiterates the importance of functions in organizing and structuring code, making it more efficient and easier to understand. The viewer is left with a clear understanding of how functions can be used to enhance their Go programming skills.
Mindmap
Keywords
π‘functions
π‘parameters
π‘main function
π‘code reuse
π‘slices
π‘range
π‘function arguments
π‘return values
π‘math package
π‘fmt package
π‘fmt.Printf
Highlights
Introduction to functions in Go programming language.
The main function in Go executes automatically when the file is run.
Creating custom functions outside of the main function for reusability.
Defining a function with a string parameter in Go.
Using `fmt.Println` and `printf` for printing output within functions.
Calling a function with a string argument to execute it.
Creating a function that takes another function as an argument.
Passing functions as arguments to iterate over slices.
Demonstrating the use of underscores (_) for ignoring indices in for loops.
Using the `range` keyword to iterate over slices in Go.
Explanation of how to return values from functions in Go.
Calculating the area of a circle using a function with a float64 argument.
Importing the `math` package to use constants like `pi` in Go.
Specifying the return type in a function signature.
Storing returned values from functions into variables.
Formatting strings to display floating-point numbers with a specific number of decimal places.
Printing formatted strings with circle areas to two decimal places.
Overall, the lesson demonstrates the creation, calling, and utilization of functions in Go for code reusability and value return.
Transcripts
all right my friends so in this video i
want to talk a little bit about
functions
in go so we've already been using
functions a little bit but not really
talking much about them we have this
main function which fires automatically
when we run the file
and also we have these functions we've
used in the past as well they're built
into go but we can also create our own
functions
which is what we're going to do in this
lesson so let's get rid of those
and what i'm going to do is create just
a simple couple of functions up here
outside
of the main function and that means that
we can use them still
inside the main function but also in the
future if we had other files we could
use them in other files as well
so let's declare our first function
which i'm going to call say greeting so
we say funk
and then the name of the function which
i'll call
say greeting and then we specify
what parameters or arguments we want to
take into this function
so i'm going to take in a string
parameter which i'm going to
say is n and that stands for name and
that is typed to be a string so this
means that we can only ever pass a
string
as an argument into this function all
right then so
inside the function itself now we can
just do something now all i'm going to
do is print something so
fmc.printline and in fact we'll use
printf so we can use a formatted string
and i'll say good
morning and then i'm going to say
percent v
so we can output a variable which is n
the name we take in and also we'll do a
new line
at the end all right then so that is a
simple function right
i'm also going to create another one
which is say bye
so say bye that also takes in a string
which we'll call
n stands for name and we're going to say
over here goodbye and then
output the variable n again all right so
let's try calling this function so all
we need to do is inside main
call the function say greeting and
invoke it
now at the minute i'm getting an error
because we have to pass in this
string so let's pass in a name which is
going to be mario
and i'm going to call this again so i'm
going to say say
greeting i'm passing a different name
luigi and then also we'll say
say oops say bye
and then pass in a name mario
like so and the reason these functions
are good is because we can basically
reuse code
over and over and over we just have to
call the function all right
so let's save this and run the file at
the bottom
and we should see three statements
printed good morning mario
good morning luigi and goodbye mario
awesome so this works
all right let me just clear this so we
have a bit of room down here
all right so that's some simple
functions
now if we wanted to we could also take
in
multiple arguments instead of just one
so let me do that i'm going to create
another function here so funk and i'm
going to call this
cycle names now this is going to take in
two arguments the first one is going to
be a name which i'll call n
and that is going to be of type slice
with strings inside it
the second one is going to be a function
so we can also pass functions in
as arguments to other functions so i'll
call that f
that is going to be of type func and
then inside this i'm going to say string
to say look this function right here
must take in a string as that argument
so this kind of matches these functions
right here
because they taking strings as arguments
so we could potentially pass one of
these
functions right here into this function
as the second argument all right
so inside here what we're going to do is
cycle through
this slice and we're going to fire this
function for each item
inside the slice and we can do that
because this slice is
strings and we pass a string into this
function
so let me do this i'm going to say 4 and
we don't need the index so i'll do
a little underscore then v for the value
and then i'm going to say colon equals
range
and it's n that we want to cycle through
which is this
slice right here and then inside that
for loop all i want to do is call a
function
so i say f and invoke it but we have to
pass in a string
we have that right here v because
remember as we cycle through this
slice right here each element is v
in the for loop so all we're doing is
calling a function for each element
inside an array
so what i could do now is call this
function cycle names down here
cycle names like so now
the first argument remember is going to
be a slice
of strings so let's create that i'm
going to pass in three names
cloud tifa
and barrett bonus points if you know
where they're from
and then the second argument is going to
be say
greeting like that now we don't invoke
it right here because that's just going
to call it right away all we're doing
is passing through a reference of that
function and we invoke it right here
inside this cycle named function so
what's going to happen
is we're passing this slice through
right here
we're going to cycle through that slice
and for each item inside it
we're going to call this say greeting
function that we also pass through
and pass in the name each time so it's
going to call this say greeting function
for each name so we should see this
printed
to the console down here several times
so let's give this a whirl i'm going to
comment out these ones for now and i'm
going to run
this file so let me save it and then run
this
and in fact before we do that let me
duplicate this
and we'll call the say by function which
is
this for each item as well so we're
going to run this function for each
of these and this function for each of
these so let me save it again
and run the file go run main dot go
and we can see all of these good
mornings and all of these
goodbyes awesome so that's pretty nice
right
all right so i want to do one more
function example and that's to show you
how we can
return values from a function because at
the minute our functions right here
all they do is print something to the
console but
it might be that in the future you have
a function that returns a value
to us so you know when we use something
like
you know length of some kind of slice it
would return to us
a number and we could store that number
in a variable if we wanted to
well i want to do something similar so
i'm going to create another
function right here and this is going to
be called circle
area and this is going to take in
an argument called r which will be a
float 64. so
a point number so something like 5.3 and
this stands for the radius right here
and by the way you see this quite a lot
in go these
single letter characters especially for
arguments
now sometimes i'm not a fan of that but
for simple functions like this it really
doesn't bother me
anyway this is going to return a value
right so we say return
something or other now it's going to
return the area of the circle and to
work
that out we need pi the value and then
we times that by r
squared so r times itself now we can get
pi
from the math package so i can import it
up here
like this math this is from the standard
library
so down here i could say math dot
pi so that's a constant on this math
library and we times that by
r and then times it by r again and this
right here this
is the formula for the area of a circle
now we're getting an error at the minute
and that's because we're returning this
value but we don't specify
in the function signature if you like
itself that we
are returning a value and if we do
return a value we have to say what type
we're returning
right here before the curly braces open
so i'm going to say we're going to
return
float 64 and now that error goes away so
this right here
is the return type all right okay then
so let's call this function
i'm gonna come down here and i'm gonna
say a1 for area one
and i'm gonna initialize that to be
equal to circle
area and then pass in some kind of value
for the radius 10.5 so remember this
returns a value this thing right here
and when it returns it
we're now storing it inside a one i'm
going to duplicate that and call this
a2 and pass in a different number over
here
i'm just going to say 15. it doesn't
matter that this is a float64 this can
be
a float as well just 15. and now
let's log those out so i'm going to say
fmt
dot print line and then a1
and a2 so we're printing both of those
out
oops i need to put my end parenthesis on
right here so let me save this now and
run it down here and now we can see
these two numbers right here so these
are the areas of the circles with these
radiuses
all right so there's a lot of decimal
places right here so i might want to
output them to two decimal places or
three decimal
places instead so let's do a formatted
string to do that
so fnt dot print
f to print a formatted string then
inside here
i'm going to say circle one is and then
percent
not point three f to output flow
and circle two is and then percents
naught point three f to output flow so
now these will be two
three decimal places all right there so
we need to pass in
a1 and a2 as well for this
and this save it and run this
once more and now we can see this looks
a bit better
so hopefully now you understand how we
can create these functions
to reuse bits of code
Browse More Related Video
Functions in Karel - Python
Functions & Methods | Java Complete Placement Course | Lecture 7
Optoelectronic devices: Introduction
42. OCR A Level (H046-H446) SLR8 - 1.2 Introduction to programming part 3 procedures & functions
First-Class and Higher-Order Functions | JavaScript π₯ | Lecture 121
Functions | Godot GDScript Tutorial | Ep 13
5.0 / 5 (0 votes)