08. Hello, World!

Go Program Order

  • package statement

  • imports statement

  • functions, variables, constants etc.

main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Pune!")
}

Package statement

  • each go file must start with package declaration.

  • package is the keyword used to declare a package.

main.go
package main
  • packages are used modularity, encapsulation, separate compilation, and reuse.

  • Go comes with lot of in-build library packages

  • crypto - cryptography related code.

  • fmt - formatted input/output related code.

  • os - operation system related code.

  • net/http - http related code.

Import statement

  • import statements are used to import external packages.

  • import is the keyword used to import a package.

main.go
import "fmt"
  • before using functionality provided by any package, it needs to be imported.

  • multiple packages can be imported using single import clause.

main.go
import (
"fmt"
"net/http"
"os"
)
  • unused imports are not allowed.

Main package

  • declaring a main package is way to telling Go that this is executable and not library.

  • Main package should have method named main for Go to be able to execute it.

  • effectively, main is starting point for application to run from a functionality point of view.

main.go
func main() {
fmt.Println("Hello, Pune!")
}

Declaring a function

  • function is a code block that can be called by name.

  • a function is declared using func keyword followed by name of function.

  • function name should be followed by round brackets ()

  • every function should have function body. This is defined using opening and closing curly braces {}

  • ideally, function can accept input in the form of function parameters and return output in form of return values.

main.go
func sayHello() {
fmt.Println("Hello, Pune!")
}

Calling a function

  • function that are in same package can be called directly by name.

  • function is called using function name followed by ()

  • functions in other packages needs to be called using package name followed by dot . and followed by function name.

main.go
func sayHello() {
fmt.Println("Hello, Pune!")
}
func main() {
sayHello()
}

Identify all the function call in code snippet below.

main.go
package main
import "fmt"
func sayHello() {
fmt.Println("Hello, Pune!")
}
func main() {
sayHello()
fmt.Println("Getting started is so easy")
fmt.Println("And fun!")
}

Guess the output

main.go
package main
import "fmt"
func main()
{
fmt.Println("Hello, Pune!")
}

Opening Brace must be on same line where function starts.