(Go Lang) Functions (GBEN)

Go by Example


  • Like C with some type inference
  • Ignore the lambda expression usage, this is just so I can run the code easily in a single source block

// Here’s a function that takes two ints and returns their sum as an int.
plus := func(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.
plusPlus := func(a, b, c int) int {
  return a + b + c

// 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)
1+2 = 3
1+2+3 = 6


Leave a Reply

Your email address will not be published. Required fields are marked *