Go (Golang) Tutorial #9 - Using Functions

Net Ninja
27 May 202110:21

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

00:00

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

05:04

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

10:07

🎯 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

Functions are blocks of code that perform a specific task and can be called upon multiple times within a program. In the video, the speaker discusses the creation and usage of functions in the Go programming language, emphasizing their role in code reusability and modularity. The main function, for instance, is a special function that runs automatically when a Go file is executed.

💡parameters

Parameters, also known as arguments, are values that are passed into a function to be used within its body. They allow functions to be dynamic and adaptable to different inputs. In the context of the video, the 'greeting' function takes a string parameter 'n' which stands for name, and this parameter is used to personalize the greeting message.

💡main function

The main function is the entry point of a Go program. It is the first function that gets executed when the program runs. In the video, the main function is where the speaker calls the custom functions they've created, like 'greeting' and 'bye', to demonstrate their functionality.

💡code reuse

Code reuse refers to the practice of using existing code in new programs or contexts, rather than rewriting similar code from scratch. Functions are a key tool for achieving code reuse, as they allow developers to encapsulate behavior in a reusable way. The video emphasizes the benefits of functions in terms of reducing redundancy and improving maintainability.

💡slices

In Go, a slice is a dynamic array that can grow or shrink in size. Slices provide a way to work with a sequence of elements from an array or a string without having to work with the entire collection. The video introduces the concept of passing a slice of strings as an argument to a function.

💡range

The 'range' keyword in Go is used to iterate over slices, arrays, strings, and maps. It provides a simple way to access each element of a collection without the need to manage indices. In the video, the speaker uses 'range' to loop through a slice of names and call a function for each element.

💡function arguments

Function arguments refer to the values or variables that are passed to a function when it is called. They enable the function to be flexible and to handle different inputs each time it is invoked. In the video, the speaker passes different names as arguments to the 'greeting' and 'bye' functions, demonstrating how function arguments work.

💡return values

Return values are the results that a function produces and sends back to the part of the program that called it. Functions can have a return type, which indicates the kind of data they will return. In the video, the 'circleArea' function calculates and returns the area of a circle based on the radius provided as an argument.

💡math package

The 'math' package is a part of the Go standard library that provides access to mathematical constants and functions. It is used to perform mathematical operations within a program. In the video, the 'math' package is imported to use the value of π (pi) for calculating the area of a circle.

💡fmt package

The 'fmt' package in Go is used for formatted I/O operations, such as printing to the console. It provides a variety of functions for outputting data in a formatted manner. In the video, the 'fmt' package is used to print messages and results to the console.

💡fmt.Printf

fmt.Printf is a function from the 'fmt' package in Go that allows for formatted printing to the console. It enables the insertion of variables into a string with specified formatting. The 'Printf' function interprets a format string and replaces format verbs, such as '%s' for strings or '%f' for floating-point numbers, with the values passed as arguments.

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

play00:02

all right my friends so in this video i

play00:04

want to talk a little bit about

play00:05

functions

play00:05

in go so we've already been using

play00:08

functions a little bit but not really

play00:10

talking much about them we have this

play00:11

main function which fires automatically

play00:13

when we run the file

play00:14

and also we have these functions we've

play00:16

used in the past as well they're built

play00:18

into go but we can also create our own

play00:20

functions

play00:20

which is what we're going to do in this

play00:22

lesson so let's get rid of those

play00:24

and what i'm going to do is create just

play00:26

a simple couple of functions up here

play00:28

outside

play00:29

of the main function and that means that

play00:32

we can use them still

play00:33

inside the main function but also in the

play00:35

future if we had other files we could

play00:37

use them in other files as well

play00:40

so let's declare our first function

play00:42

which i'm going to call say greeting so

play00:44

we say funk

play00:45

and then the name of the function which

play00:48

i'll call

play00:49

say greeting and then we specify

play00:52

what parameters or arguments we want to

play00:55

take into this function

play00:56

so i'm going to take in a string

play00:58

parameter which i'm going to

play01:00

say is n and that stands for name and

play01:02

that is typed to be a string so this

play01:05

means that we can only ever pass a

play01:06

string

play01:07

as an argument into this function all

play01:09

right then so

play01:10

inside the function itself now we can

play01:12

just do something now all i'm going to

play01:14

do is print something so

play01:16

fmc.printline and in fact we'll use

play01:19

printf so we can use a formatted string

play01:22

and i'll say good

play01:24

morning and then i'm going to say

play01:26

percent v

play01:27

so we can output a variable which is n

play01:31

the name we take in and also we'll do a

play01:33

new line

play01:34

at the end all right then so that is a

play01:37

simple function right

play01:38

i'm also going to create another one

play01:40

which is say bye

play01:43

so say bye that also takes in a string

play01:47

which we'll call

play01:47

n stands for name and we're going to say

play01:51

over here goodbye and then

play01:54

output the variable n again all right so

play01:57

let's try calling this function so all

play01:59

we need to do is inside main

play02:02

call the function say greeting and

play02:04

invoke it

play02:05

now at the minute i'm getting an error

play02:06

because we have to pass in this

play02:08

string so let's pass in a name which is

play02:11

going to be mario

play02:12

and i'm going to call this again so i'm

play02:14

going to say say

play02:16

greeting i'm passing a different name

play02:20

luigi and then also we'll say

play02:23

say oops say bye

play02:26

and then pass in a name mario

play02:29

like so and the reason these functions

play02:32

are good is because we can basically

play02:33

reuse code

play02:34

over and over and over we just have to

play02:36

call the function all right

play02:38

so let's save this and run the file at

play02:41

the bottom

play02:43

and we should see three statements

play02:45

printed good morning mario

play02:47

good morning luigi and goodbye mario

play02:49

awesome so this works

play02:50

all right let me just clear this so we

play02:52

have a bit of room down here

play02:54

all right so that's some simple

play02:56

functions

play02:57

now if we wanted to we could also take

play03:00

in

play03:01

multiple arguments instead of just one

play03:03

so let me do that i'm going to create

play03:05

another function here so funk and i'm

play03:06

going to call this

play03:07

cycle names now this is going to take in

play03:11

two arguments the first one is going to

play03:12

be a name which i'll call n

play03:14

and that is going to be of type slice

play03:16

with strings inside it

play03:18

the second one is going to be a function

play03:20

so we can also pass functions in

play03:22

as arguments to other functions so i'll

play03:25

call that f

play03:26

that is going to be of type func and

play03:27

then inside this i'm going to say string

play03:30

to say look this function right here

play03:33

must take in a string as that argument

play03:36

so this kind of matches these functions

play03:38

right here

play03:39

because they taking strings as arguments

play03:41

so we could potentially pass one of

play03:44

these

play03:44

functions right here into this function

play03:47

as the second argument all right

play03:49

so inside here what we're going to do is

play03:52

cycle through

play03:53

this slice and we're going to fire this

play03:55

function for each item

play03:57

inside the slice and we can do that

play03:58

because this slice is

play04:00

strings and we pass a string into this

play04:02

function

play04:04

so let me do this i'm going to say 4 and

play04:06

we don't need the index so i'll do

play04:08

a little underscore then v for the value

play04:11

and then i'm going to say colon equals

play04:14

range

play04:15

and it's n that we want to cycle through

play04:17

which is this

play04:18

slice right here and then inside that

play04:20

for loop all i want to do is call a

play04:22

function

play04:22

so i say f and invoke it but we have to

play04:25

pass in a string

play04:27

we have that right here v because

play04:29

remember as we cycle through this

play04:31

slice right here each element is v

play04:34

in the for loop so all we're doing is

play04:38

calling a function for each element

play04:40

inside an array

play04:42

so what i could do now is call this

play04:45

function cycle names down here

play04:47

cycle names like so now

play04:50

the first argument remember is going to

play04:52

be a slice

play04:54

of strings so let's create that i'm

play04:57

going to pass in three names

play04:59

cloud tifa

play05:04

and barrett bonus points if you know

play05:07

where they're from

play05:08

and then the second argument is going to

play05:10

be say

play05:12

greeting like that now we don't invoke

play05:14

it right here because that's just going

play05:15

to call it right away all we're doing

play05:17

is passing through a reference of that

play05:19

function and we invoke it right here

play05:21

inside this cycle named function so

play05:24

what's going to happen

play05:25

is we're passing this slice through

play05:28

right here

play05:29

we're going to cycle through that slice

play05:31

and for each item inside it

play05:33

we're going to call this say greeting

play05:35

function that we also pass through

play05:37

and pass in the name each time so it's

play05:39

going to call this say greeting function

play05:41

for each name so we should see this

play05:43

printed

play05:44

to the console down here several times

play05:46

so let's give this a whirl i'm going to

play05:48

comment out these ones for now and i'm

play05:51

going to run

play05:52

this file so let me save it and then run

play05:55

this

play05:55

and in fact before we do that let me

play05:58

duplicate this

play05:59

and we'll call the say by function which

play06:02

is

play06:02

this for each item as well so we're

play06:04

going to run this function for each

play06:06

of these and this function for each of

play06:08

these so let me save it again

play06:10

and run the file go run main dot go

play06:15

and we can see all of these good

play06:16

mornings and all of these

play06:18

goodbyes awesome so that's pretty nice

play06:20

right

play06:22

all right so i want to do one more

play06:24

function example and that's to show you

play06:25

how we can

play06:26

return values from a function because at

play06:29

the minute our functions right here

play06:31

all they do is print something to the

play06:32

console but

play06:34

it might be that in the future you have

play06:35

a function that returns a value

play06:38

to us so you know when we use something

play06:40

like

play06:41

you know length of some kind of slice it

play06:44

would return to us

play06:45

a number and we could store that number

play06:47

in a variable if we wanted to

play06:48

well i want to do something similar so

play06:51

i'm going to create another

play06:52

function right here and this is going to

play06:54

be called circle

play06:57

area and this is going to take in

play07:01

an argument called r which will be a

play07:03

float 64. so

play07:05

a point number so something like 5.3 and

play07:08

this stands for the radius right here

play07:10

and by the way you see this quite a lot

play07:12

in go these

play07:13

single letter characters especially for

play07:15

arguments

play07:16

now sometimes i'm not a fan of that but

play07:18

for simple functions like this it really

play07:20

doesn't bother me

play07:21

anyway this is going to return a value

play07:23

right so we say return

play07:25

something or other now it's going to

play07:27

return the area of the circle and to

play07:29

work

play07:30

that out we need pi the value and then

play07:32

we times that by r

play07:33

squared so r times itself now we can get

play07:36

pi

play07:37

from the math package so i can import it

play07:40

up here

play07:41

like this math this is from the standard

play07:44

library

play07:45

so down here i could say math dot

play07:48

pi so that's a constant on this math

play07:50

library and we times that by

play07:52

r and then times it by r again and this

play07:55

right here this

play07:56

is the formula for the area of a circle

play07:59

now we're getting an error at the minute

play08:01

and that's because we're returning this

play08:02

value but we don't specify

play08:04

in the function signature if you like

play08:05

itself that we

play08:07

are returning a value and if we do

play08:10

return a value we have to say what type

play08:12

we're returning

play08:13

right here before the curly braces open

play08:15

so i'm going to say we're going to

play08:16

return

play08:17

float 64 and now that error goes away so

play08:20

this right here

play08:21

is the return type all right okay then

play08:25

so let's call this function

play08:26

i'm gonna come down here and i'm gonna

play08:29

say a1 for area one

play08:31

and i'm gonna initialize that to be

play08:33

equal to circle

play08:35

area and then pass in some kind of value

play08:39

for the radius 10.5 so remember this

play08:42

returns a value this thing right here

play08:44

and when it returns it

play08:46

we're now storing it inside a one i'm

play08:48

going to duplicate that and call this

play08:50

a2 and pass in a different number over

play08:54

here

play08:54

i'm just going to say 15. it doesn't

play08:56

matter that this is a float64 this can

play08:58

be

play08:59

a float as well just 15. and now

play09:02

let's log those out so i'm going to say

play09:04

fmt

play09:05

dot print line and then a1

play09:10

and a2 so we're printing both of those

play09:13

out

play09:14

oops i need to put my end parenthesis on

play09:16

right here so let me save this now and

play09:19

run it down here and now we can see

play09:23

these two numbers right here so these

play09:25

are the areas of the circles with these

play09:27

radiuses

play09:28

all right so there's a lot of decimal

play09:31

places right here so i might want to

play09:33

output them to two decimal places or

play09:35

three decimal

play09:36

places instead so let's do a formatted

play09:38

string to do that

play09:39

so fnt dot print

play09:42

f to print a formatted string then

play09:44

inside here

play09:45

i'm going to say circle one is and then

play09:48

percent

play09:49

not point three f to output flow

play09:52

and circle two is and then percents

play09:56

naught point three f to output flow so

play09:58

now these will be two

play09:59

three decimal places all right there so

play10:02

we need to pass in

play10:03

a1 and a2 as well for this

play10:07

and this save it and run this

play10:10

once more and now we can see this looks

play10:13

a bit better

play10:14

so hopefully now you understand how we

play10:17

can create these functions

play10:18

to reuse bits of code

Rate This

5.0 / 5 (0 votes)

Related Tags
GoLangFunction TutorialCode ReusabilityParameter PassingFunction ArgumentsValue ReturnProgramming ConceptsSoftware DevelopmentGo FunctionsCircle Area Calculation