GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing gobyexample.com — Go by Example: 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 their sum as an int.

func plus(a int, b int) int {

Go requires explicit returns, i.e. it won’t automatically return the value of the last expression.

    return a + b
}

When you have multiple consecutive parameters of the same type, you may omit the type name for the like-typed parameters up to the final parameter that declares the type.

func plusPlus(a, b, c int) int {
    return a + b + c
}
func main() {

Call a function just as you’d expect, with name(args).

    res := plus(1, 2)
    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

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.