BeginnerLesson 1 of 15
Hello World & Program Structure – Go
Package, import, the main function and formatted output.
Every Go program consists of packages. Executable programs live in package main and start in the function main. With import you bring in packages from the standard library, e.g. fmt for output.
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
fmt.Println("I am learning", "Go", 42) // Println separates values with spaces
}Println appends a line break, Print does not. With Printf you format using placeholders (verbs): %s text, %d integer, %f floating-point number, %v any value, %T type, %q quoted text.
package main
import "fmt"
func main() {
name, alter := "Ada", 36
fmt.Printf("%s is %d years old\n", name, alter)
fmt.Printf("%v %T %q %.2f\n", alter, alter, name, 3.14159) // 36 int "Ada" 3.14
text := fmt.Sprintf("%05d|%-6s|%6s", 42, "ab", "cd")
fmt.Println(text) // 00042|ab | cd
}Comments start with // (single line) or are enclosed in /* ... */. Comments directly above a function serve as documentation and by convention begin with the function name. Statements need no semicolon – the compiler inserts it itself at the end of the line.
package main
import "fmt"
// Gruss returns a greeting for the given name.
func Gruss(name string) string {
return "Hello, " + name + "!"
}
func main() {
fmt.Println(Gruss("Ada"))
}TipThe opening curly brace must be on the same line as
func or if – otherwise the compiler reports a syntax error. go fmt formats everything automatically.