Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Go Language Overview!
You have completed Go Language Overview!
Preview
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
You set this up by declaring multiple
return values within parentheses,
0:00
following the parentheses that
accept parameters for the function.
0:01
So here, we specify that this squareRoot
function is going to return one value
0:05
that's a float64 type, and
then a second value that's an error type.
0:10
Now, as you might be aware,
0:15
it's not possible to take a square
root of a negative number.
0:17
So, we've set our square root
function up to check for this.
0:21
It looks at the parameter
that got passed in, x, and
0:23
if it's less than 0 then we return
the value 0, which we're going to ignore.
0:27
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