Categories
Mini-Programs

Go Read File Content Into a Slice

Demofile.txt

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

package main

import (
	"fmt"
	"io/ioutil"
	"strings"
)

func main() {
	contents, err := ioutil.ReadFile("demofile.txt")
	if err != nil {
		fmt.Println("Error reading file")
	}
	words := strings.Split(string(contents)," ")
	fmt.Println(len(words), words)

10 [Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!]
Categories
Mini-Programs

Go Open File

Open a File on your local storage media

Assume we have the following file, located in the same folder as Go main program that open a file.

Demofile.txt

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	content, err := ioutil.ReadFile("demofile.txt")
	if err != nil {
		fmt.Println("Error reading file")
	}
	fmt.Print(string(content))
}

Output:

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Categories
Mini-Programs

Go User Input

User Input

Go allows for user input.

That means we are able to ask the user for input.

package main

import (
	"fmt"
	"bufio"
	"os"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print("Enter any character:")
	scanner.Scan()
	input := scanner.Text()
	fmt.Printf("You type: %q", input)
}
Categories
Data Structure and Algorithm Mini-Programs

FizzBuzz

For numbers which are divisible of both 3 and 5, print “FizzBuzz” instead of the number. Divisible by 3 print “Fizz” and divisible by 5 print “Buzz”

package main

import (
	"fmt"
)

func fizzBuzz(num int) {
	for v := 1; v <= num; v++ {
		if  v % 15 == 0  {
			fmt.Println("v:", v, "FizzBuzz")
		} else if v % 5 == 0 {
				fmt.Println("v:", v, "Buzz")
			} else if v % 3 == 0 {
				fmt.Println("v:", v, "Fizz")
			} else {
			fmt.Println("v:", v)
		}
	}
}

func main() {
	fizzBuzz(20)
}