1. Go Syntax & Structure
Hello World
package main // Declares the package (main is the entry point) import "fmt" // Import the "fmt" package for input/output func main() { fmt.Println("Hello, World!") // Prints to the console }
- Key Points:
- Every Go file starts with package <name>. Use package main for executable programs.
- func main() is the entry point of the program.
- Use import to include external packages (like fmt for formatting).
2. Variables & Data Types
Variable Declaration
var name string = "Alice" // Explicit type declaration age := 25 // Type inferred (short declaration, only inside functions) pi := 3.14 // Type inferred as float64 isStudent := true // Boolean
- Data Types:
- Basic types: string, int, float64, bool.
- Zero values: Uninitialized variables default to 0, "", false, etc.
3. Control Structures
If/Else
temperature := 30 if temperature > 28 { fmt.Println("It's hot!") } else if temperature < 10 { fmt.Println("It's cold!") } else { fmt.Println("It's pleasant.") }
For Loop (Go has no while keyword)
// Classic for loop for i := 0; i < 5; i++ { fmt.Println(i) } // While-like loop count := 0 for count < 3 { fmt.Println(count) count++ }
Switch
day := "Monday" switch day { case "Monday": fmt.Println("Workday") case "Saturday", "Sunday": fmt.Println("Weekend") default: fmt.Println("Midweek") }
4. Functions
Basic Function
func add(a int, b int) int { return a + b } result := add(3, 5) // result = 8
Multiple Return Values
func divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("cannot divide by zero") } return a / b, nil } quotient, err := divide(10, 2) // Handle the error
5. Packages & Imports
- Custom Package:
- Create a file math/math.go:
package math // Declare the package name func Multiply(a, b int) int { return a * b }
- Use it in main.go:
import "your-module-name/math" // Replace with your module name func main() { product := math.Multiply(4, 5) // 20 }
6. Error Handling
Go uses explicit error returns (no exceptions):
file, err := os.Open("data.txt") if err != nil { log.Fatal(err) // Handle the error } defer file.Close() // Ensure the file closes when the function exits
Summary of Key Concepts
- Syntax: package, import, func, {} for code blocks.
- Variables: Use var or := (short declaration).
- Control Structures: if, for (no while), switch.
- Functions: Can return multiple values, including errors.
- Packages: Organize code into reusable modules.
Discussions
Login to Post Comments