Go Learning Path - Module 1: Hello World & Basic Concepts
go教程目录
Module 1: Hello World & Basic Concepts
Module 2: Variables, Data Types, and Constants
Module 3: Functions, Methods, and Packages
Module 4: Control Structures (if/else, loops)
Module 5: Arrays, Slices, and Maps Arrays
Module 6: Structs and Interfaces
Module 7: Pointers and Memory Management
Module 8: Concurrency with Goroutines and Channels
Module 9: Error Handling and Defer/Panic/Recover
Module 10: Advanced Topics - Testing and Standard Library
Welcome to Go programming! Go (also known as Golang) is a statically typed, compiled programming language designed at Google. This module introduces you to the basics of Go.
Hello World Program
Let's start with the classic "Hello, World!" program:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Explanation:
-
package main- Every Go program starts with a package declaration. Themainpackage is special - it defines a standalone executable program. -
import "fmt"- Imports thefmtpackage which provides formatted I/O functions. -
func main()- The entry point function that gets executed when the program runs. -
fmt.Println()- Prints the string followed by a newline.
How to Run Go Programs
Save your code in a file ending with .go extension (e.g., hello.go) and run:
go run hello.go
To compile and generate an executable:
go build hello.go
./hello # On Unix/Linux/Mac
hello.exe # On Windows
Package Declaration
Every Go program belongs to a package. Packages help organize and reuse code:
package main // For executable programs
// Or for libraries
package utils // A reusable package named 'utils'
Import Statements
You can import multiple packages:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Square root of 16 is:", math.Sqrt(16))
}
Comments
Go supports single-line and multi-line comments:
// This is a single-line comment
/*
This is a
multi-line comment
*/
Exercises
-
Modify the hello world program to print your name.
-
Create a program that prints multiple lines using multiple
Printlnstatements. -
Experiment with the
fmt.Print()function to see how it differs fromfmt.Println().