0% found this document useful (0 votes)
20 views1 page

Go by Example - Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views1 page

Go by Example - Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Go by Example: Functions https://gobyexample.

com/functions

Go by Example: Functions
Functions are central in Go. We’ll learn about
functions with a few different examples.

package main

import "fmt"

Here’s a function that takes two ints and returns func plus(a int, b int) int {
their sum as an int.

Go requires explicit returns, i.e. it won’t return a + b


automatically return the value of the last }
expression.

When you have multiple consecutive parameters func plusPlus(a, b, c int) int {
of the same type, you may omit the type name for return a + b + c
the like-typed parameters up to the final }
parameter that declares the type.

func main() {

Call a function just as you’d expect, with res := plus(1, 2)


name(args). fmt.Println("1+2 =", res)

res = plusPlus(1, 2, 3)
fmt.Println("1+2+3 =", res)
}

$ go run functions.go
1+2 = 3
1+2+3 = 6

There are several other features to Go functions.


One is multiple return values, which we’ll look at
next.

Next example: Multiple Return Values.

by Mark McGranaghan and Eli Bendersky | source | license

1 of 1 11/26/24, 23:27

You might also like