DMarlon Studio

Lesson 1 · 1 of 20

Hello, world · Go

Write your first Go program: package main, the main function and fmt.Println to show text and numbers in the console.

Go · Hello, world in DMarlon Studio: the example's code and its output in the terminal

Every Go program starts with package main: it says the file is a program you can run, not a library. Execution begins in the function func main(), and the braces { } mark where it starts and ends.

import "fmt" brings in the fmt package, the one that prints and formats text. Its functions are called with the package name in front: fmt.Println. Go does not let you import a package you do not use: if one is left over, the program will not compile.

fmt.Println prints its values separated by a space and ends the line. It takes text in double quotes and numbers, and it works things out before printing: "2 + 3 =", 2+3 shows 2 + 3 = 5.

fmt.Print does not end the line and puts no space between two strings; that is why the second one ends in \n, the newline character, and the two pieces make Step by step. An empty fmt.Println() leaves a blank line.

The program runs with go run main.go, which compiles and runs it in one step. In DMarlon Studio, Go is also the server of the Web (Go) target, so what you learn in this course will be useful there.

Code · main.go

// Every Go program starts in package main, at func main.package mainimport "fmt" // the package for printing textfunc main() {	fmt.Println("Hello, world!")	fmt.Println("Welcome to the Go course.")	// Println puts spaces between its values and ends the line.	fmt.Println("Lessons:", 20, "Level:", "basic")	fmt.Println("2 + 3 =", 2+3)	// Print adds no newline: \n ends the line.	fmt.Print("Step ")	fmt.Print("by step\n")	// An empty Println writes a blank line.	fmt.Println()	fmt.Println("Bye!")}

Output · go run main.go

Hello, world!
Welcome to the Go course.
Lessons: 20 Level: basic
2 + 3 = 5
Step by step

Bye!

Key points

  • A program starts at package main and func main().
  • import "fmt" gives you fmt.Println and fmt.Print.
  • Println adds spaces and a newline; Print does not.
  • \n is a newline inside a string.
  • go run main.go compiles and runs.

Exercise

Write a program that shows your name, your city and, on another line, how many days there are in three weeks, working it out with 3*7.