Go Code Snippets
Below are some useful Go code snippets for use in everyday projects.
Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.
package main import ( "fmt" "math/rand" "time" ) func main() { // Minimum and maximum values for random number. minVal := 1 maxVal := 59 // Set up random number source. source := rand.New(rand.NewSource(time.Now().UnixNano())) randSource := rand.New(source) // Generate random number. randomNumber := randSource.Intn(maxVal-minVal+1) + minVal // Display the result in the console or terminal. fmt.Println(randomNumber) }
A text file can be read from and processed line by line.
package main import ( "bufio" "fmt" "os" ) func main() { // Open file, assign to variable, along with any errors. readFile, err := os.Open("C:\\demo\\demo.txt") // Check for any errors in opening the file. if err != nil { // Display error. fmt.Println(err) } else { // Prepare the file for reading. filescanner := bufio.NewScanner(readFile) filescanner.Split(bufio.ScanLines) // Process the lines in the file. for filescanner.Scan() { // Display the line in the console/terminal. fmt.Println(filescanner.Text()) } } // Close the file. readFile.Close() }