Created
June 17, 2024 15:18
-
-
Save JettIsOnTheNet/de2f8b1192de4f7da83b0007825182cd to your computer and use it in GitHub Desktop.
Syntax example scan sheet for Golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Go scan sheet / Cheat Sheet | |
// main package | |
package main | |
// imports | |
import ( | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
// define a struct | |
type Person struct { | |
FirstName string | |
LastName string | |
Age int | |
} | |
// functions | |
func greet(name string) string { | |
return "Hello " + name + "!" | |
} | |
// variables | |
func main() { | |
// creating an instance of Person | |
person1 := Person{"John", "Doe", 30} | |
// accessing fields of the struct | |
fmt.Println("First Name:", person1.FirstName) | |
fmt.Println("Last Name:", person1.LastName) | |
fmt.Println("Age:", person1.Age) | |
// instance with field names | |
person2 := Person{ | |
FirstName: "Alice", | |
LastName: "Smith", | |
Age: 28, | |
} | |
var integerVar int = 10 | |
stringVar := "Hello, Go!" | |
// functions | |
fmt.Println(greet("World")) | |
// loops | |
// for loop | |
for i := 0; i < 5; i++ { | |
fmt.Println("For loop iteration:", i) | |
} | |
// conditional Statements | |
if integerVar > 5 { | |
fmt.Println("Integer is greater than 5") | |
} else if integerVar == 5 { | |
fmt.Println("Integer is 5") | |
} else { | |
fmt.Println("Integer is less than 5") | |
} | |
// conditional statements using switch | |
switch { | |
case integerVar > 5: | |
fmt.Println("Integer is greater than 5") | |
case integerVar == 5: | |
fmt.Println("Integer is 5") | |
default: | |
fmt.Println("Integer is less than 5") | |
} | |
// data structures | |
mySlice := []int{1, 2, 3, 4, 5} | |
myMap := map[string]int{"a": 1, "b": 2} | |
// error handling | |
_, err := os.Open("nonexistent_file.txt") | |
if err != nil { | |
fmt.Println("Error opening file:", err) | |
} | |
// concurrency | |
c := make(chan int) | |
go sum(mySlice, c) | |
fmt.Println("Sum from channel:", <-c) | |
// writing to a file | |
content := []byte("Writing to a file in Go!") | |
ioutil.WriteFile("example.txt", content, 0644) | |
// reading from a file | |
data, _ := ioutil.ReadFile("example.txt") | |
fmt.Println("File content:", string(data)) | |
} | |
// goroutine for summing elements | |
func sum(slice []int, c chan int) { | |
sum := 0 | |
for _, value := range slice { | |
sum += value | |
} | |
c <- sum // send sum to channel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment