點燈坊

失くすものさえない今が強くなるチャンスよ

Function Overview

Sam Xiao's Avatar 2022-03-10

We can use func keyword to define a function.

Version

Golang 1.17.7

Function

main.go

package main

import "fmt"

func main() {
    result := add(1, 2)
    fmt.Println(result)
}

func add(x, y int) int {
    return x + y
}

Line 1

package main

Declare main package for the executable program.

Line 3

import "fmt"

Import fmt package for using fmt.Println().

Line 5

func main() {
    result := add(1, 2)
    fmt.Println(result)
}

main() is a special function and it’s the entry point of the executable program.

  • Go is not an OOP-only language. We can define function directly
  • func : define a function with func keyword
  • := : define a variable without type. The type is inferred automatically by Type Inference
  • fmt.Println : print out the result

Line 10

func add(x, y int) int {
    return x + y
}

add() is a user-defined function.

  • x, y int : parameter x and y are all type int. We can ignore to declare type int on the first parameter
  • func add() int : declare return type int of the function

We don’t have to define add() before using main()

overview000

Conclusion

  • func keyword is so concise to define a function
  • We don’t have to use : to declare parameter type and function return type
  • We can use := to define a local variable in the function instead of var