08. Hello, World!

Go Program Order

  • package statement
  • imports statement
  • functions, variables, constants etc.
main.go
1
package main
2
3
import "fmt"
4
5
func main() {
6
fmt.Println("Hello, Pune!")
7
}
Copied!

Package statement

  • each go file must start with package declaration.
  • package is the keyword used to declare a package.
main.go
1
package main
Copied!
  • packages are used modularity, encapsulation, separate compilation, and reuse.
  • Go comes with lot of in-build library packages
Standard library - pkg.go.dev
  • 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
1
import "fmt"
Copied!
  • before using functionality provided by any package, it needs to be imported.
  • multiple packages can be imported using single import clause.
main.go
1
import (
2
"fmt"
3
"net/http"
4
"os"
5
)
Copied!
  • 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
1
func main() {
2
fmt.Println("Hello, Pune!")
3
}
Copied!

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
1
func sayHello() {
2
fmt.Println("Hello, Pune!")
3
}
Copied!

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
1
func sayHello() {
2
fmt.Println("Hello, Pune!")
3
}
4
func main() {
5
sayHello()
6
}
Copied!
Identify all the function call in code snippet below.
main.go
1
package main
2
3
import "fmt"
4
5
func sayHello() {
6
fmt.Println("Hello, Pune!")
7
}
8
func main() {
9
sayHello()
10
fmt.Println("Getting started is so easy")
11
fmt.Println("And fun!")
12
}
13
Copied!
The Go Playground
Guess the output
main.go
1
package main
2
3
import "fmt"
4
5
func main()
6
{
7
fmt.Println("Hello, Pune!")
8
}
Copied!
Opening Brace must be on same line where function starts.
Last modified 2yr ago