Golang Website API Development
Go Basics
Your First Go Program
Go is a programming language created at Google. It's known for being simple, efficient, and easy to read. Let's start by getting it set up on your machine.
The best way to install Go is from the official website, go.dev. The site provides installers for Windows, macOS, and Linux. If you just want to try things out without installing anything, you can use the Go Playground, an online tool that lets you run Go code right in your browser.
Once you have Go ready, let's write a classic "Hello, World!" program. Create a new file named hello.go and type the following:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
Let's break this down:
package main: Every Go program is made up of packages. Themainpackage is special; it tells the Go compiler that the program is executable, meaning it's a program we can run.import "fmt": This line imports thefmtpackage, which is short for "format". It contains functions for formatting text and printing things to the screen.func main(): This is the main function where the program execution begins.
To run this code from your terminal, navigate to the directory where you saved hello.go and run the command go run hello.go. You should see Hello, Go! printed to your screen.
Variables and Data
Variables are containers for storing data. In Go, you must declare the type of data a variable will hold. This is called static typing, and it helps prevent bugs by ensuring you don't accidentally mix a number with a piece of text.
Here are some of the basic data types:
| Type | Description | Example |
|---|---|---|
int | Integers (whole numbers) | 42, -10 |
float64 | Floating-point numbers (decimals) | 3.14, 99.9 |
string | A sequence of characters (text) | "Hello" |
bool | A boolean value | true, false |
You can declare a variable in a couple of ways. The long form specifies the type explicitly, while the short form lets Go figure it out for you.
package main
import "fmt"
func main() {
// Long form with `var`
var age int = 30
// Short form with `:=` (most common)
name := "Alice"
isLearning := true
fmt.Println(name, "is", age, "years old.")
fmt.Println("Is learning Go?", isLearning)
}
The
:=syntax is a shortcut for declaring and initializing a variable. It can only be used inside functions.
Controlling the Flow
Programs often need to make decisions or repeat actions. Control structures let you direct the flow of your code. Go has a few simple ones you'll use all the time.
The most basic decision-maker is the
ifstatement. If a condition is true, the code inside the block runs.
score := 85
if score >= 60 {
fmt.Println("You passed!")
} else {
fmt.Println("You did not pass.")
}
Go only has one looping construct: the for loop. It's versatile and can be used in several ways. The most common form has three parts: an initializer, a condition, and a post-statement.
// A classic for loop
for i := 0; i < 3; i++ {
fmt.Println(i)
}
// Output: 0, 1, 2
You can also use for like a while loop from other languages by just providing a condition.
count := 3
for count > 0 {
fmt.Println(count)
count-- // same as count = count - 1
}
// Output: 3, 2, 1
Functions
Functions are reusable blocks of code that perform a specific task. They help organize your program and make it more readable. You've already used one: main.
Here’s how you define a function that takes two integers as input and returns their sum.
parameter
noun
A special variable used in a function to refer to one of the pieces of data provided as input.
package main
import "fmt"
// add takes two integers and returns their sum as an integer.
func add(a int, b int) int {
return a + b
}
func main() {
result := add(5, 3)
fmt.Println("5 + 3 =", result) // Prints 8
}
In the add function definition, (a int, b int) are the parameters, and the int after the parentheses is the return type. This tells Go that the add function must return an integer.
If multiple parameters have the same type, you can write the type just once.
For example,
func add(a, b int) intis a shorter way to write the same function header.
What is the purpose of the package main declaration in a Go source file?
Which command is used to compile and run a Go source file named app.go from the terminal?