Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Declaring a function consists of providing a function name, names and types of any parameters, and one or more return values.
- Declaring a function
-
func
keyword - Function name
- Parentheses
- Code block in curly braces that gets run when function is called
-
package main
import "fmt"
func main() {
myFunction()
}
func myFunction() {
fmt.Println("Running myFunction")
}
-
Naming rules
- Same naming rules as variables, types, etc.
- Must start with letter
- Capital letter means exported from the current package, lower case means unexported
- Convention is to use camelCase for multiple words
Can declare parameters:
package main
import "fmt"
func main() {
square(3)
add(2, 4)
subtract(10, 3)
}
func square(number int) {
fmt.Println(number * number)
}
func add(a float64, b float64) {
fmt.Println(a + b)
}
func subtract(a, b float64) {
fmt.Println(a - b)
}
Parameters are type enforced.
square("hello")
fails at compile time.-
Return values
- Must specify return value type.
- Can name return values - sometimes useful as documentation.
- Can use bare returns if return values are named.
package main
import "fmt"
func main() {
fmt.Println(square(3))
fmt.Println(add(2, 4))
fmt.Println(subtract(10, 3))
}
func square(number int) int {
return number * number
}
func add(a float64, b float64) (sum float64) {
return a + b
}
func subtract(a, b float64) (difference float64) {
difference = a - b
return
}
- Compile error if last statement of function is not a
return
, because that line of code will never be reached.
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 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