Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
It's possible to return multiple values from a Go function. This is usually used to communicate errors.
- Can return multiple values from a function. Usually used to communicate errors.
package main
import (
"fmt"
"log"
"math"
)
func main() {
squareRoot, err := squareRoot(9)
if err != nil {
log.Fatal(err)
}
fmt.Println(squareRoot)
}
func squareRoot(x float64) (float64, error) {
if x < 0 {
return 0, fmt.Errorf("can't take square root of negative number")
}
return math.Sqrt(x), nil
}
- Can ignore a return value by assigning to blank identifier,
_
.- This code gives a compile error:
package main
import (
"fmt"
"os"
)
func main() {
fileInfo := os.Stat("existent.txt")
fmt.Println(fileInfo.Size())
fileInfo = os.Stat("nonexistent.txt")
fmt.Println(fileInfo.Size())
}
- We can get it to compile by adding blank identifiers.
- But this isn't always a good idea. In this case, checking the size of "existent.txt" works, because the file exists. But our users get a panic, a runtime error, when we try to get the size of "nonexistent.txt", because the file doesn't exist.
- We can fix this by checking to see if the error value is anything other than nil, and handling the error if it is.
package main
import (
"fmt"
"os"
)
func main() {
fileInfo, error := os.Stat("existent.txt")
if error != nil {
fmt.Println(error)
} else {
fmt.Println(fileInfo.Size())
}
fileInfo, error = os.Stat("nonexistent.txt")
if error != nil {
fmt.Println(error)
} else {
fmt.Println(fileInfo.Size())
}
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
It's possible to return multiple
values from a single function.
0:00
This is usually used
to communicate errors.
0:03
You set this up by declaring multiple
return values within parentheses,
0:06
following the parentheses that
accept parameters for the function.
0:10
So here, we specify that this squareRoot
function is going to return one value
0:14
that's a float64 type, and
then a second value that's an error type.
0:19
Now, as you might be aware,
0:24
it's not possible to take a square
root of a negative number.
0:26
So, we've set our square root
function up to check for this.
0:30
It looks at the parameter
that got passed in, x, and
0:32
if it's less than 0 then we return
the value 0, which we're going to ignore.
0:36
As well as the new error value, which we
get by calling the format packages Errorf
0:41
function, and passing it a string, can't
take the square root of a negative number.
0:47
If x is greater than 0, or equal to 0,
then we'll proceed as normal.
0:53
We call the math packages
square root function and
0:58
pass it the parameter that we got.
1:01
We then return the value nil,
which represents that we have no error.
1:05
We then handle those multiple return
values up here in the main function.
1:09
We call square root, up here, and
1:14
then we assign two variables at
once based on its return value.
1:17
The square root variable will hopefully
contain the square root of whatever
1:21
argument we pass the square root.
1:25
And the error value will hopefully be nil.
1:27
But in the event that there was a problem,
say if we were to call square
1:30
root with a negative number,
the error value will not be nil.
1:34
We'll have passed the return
value of this error f function,
1:38
which will be an error value,
which will then logout to the console.
1:45
Calling the fatal function
from the log packages cause
1:50
your program to print an error message and
then exit immediately.
1:55
So this line down here would never
be reached if there was an error.
1:59
So, we handled the error here and
2:03
in the event that there's not an error
we proceed to print out the square root.
2:04
So let's try running this.
2:10
Okay, and because we called square
root with a negative number we see
2:13
our error message printed out here, can't
take square root of a negative number.
2:17
Where as if we were to change this to a
valid value say get the square root of 9,
2:21
if we try running this again
it runs successfully and
2:27
it prints out our square root, 3.
2:31
These function calls also
return multiple values.
2:34
But in this case we're getting a compile
error because we aren't doing anything
2:37
with the second value We're getting the
multiple value os.Stat() in single value
2:41
context.
2:46
We can get this code to compile
by adding the blank identifier.
2:48
This will assign the second value,
the error value,
2:53
from os.Stat to a throwaway variable,
this underscore that you see here.
2:56
So if we have this down here as well
our program will then compile and run.
3:04
So as you can see up
here that we get a file
3:07
size for the existent text file.
3:13
However down here we get a run time panic,
this is a special type of
3:18
error that occurs after your program
compiles and while it's running.
3:23
And that's something that you
want to avoid wherever possible.
3:29
And this is why that assigning error
values to the blank identifier isn't
3:32
always a good idea.
3:36
In this case, checking the size
of the existent.txt file worked
3:38
because that file was on the disk,
but, nonexistent.txt wasn't.
3:42
And therefore we got an error which
we ignored and when we tried to print
3:48
out the size on this invalid file
info object, our program panicked.
3:53
We can fix this by checking to see if
the error return value from os.stat
3:59
is anything other than nil.
4:03
And if it is, handling the error.
4:05
So instead of the blank identifier here,
4:07
let's assign this error return
value to a variable called error.
4:09
And here let's do a test.
4:14
Let's say if the error
Is not equal to nil.
4:16
Then we will print out the error.
4:24
And if the error is nil, it means that
we got our file info back successfully.
4:31
So we can move this format
print line file info.
4:35
Size line up into the else clause.
4:40
And we'll be able to print
the file info out successfully.
4:47
We'll do the same down here following
getting os.stat for the second file.
4:50
We need to be sure to assign
not to the blank Identifier,
4:56
but to the error variable.
5:00
We'll test if it's nil.
5:03
If it's not nil,
we'll print out the error.
5:04
Otherwise, we'll print out the file info.
5:06
Now let's try running this again.
5:09
And you see for
our first file we got a file size of 0,
5:12
which, because it does exist but
its size is 0.
5:15
And for
the second file it prints out our error.
5:19
It tried to run stats on nonexistant.txt,
but there was no such file.
5:22
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up