I have three GO projects in mind, but I'm afraid to finish them. I want to do it and have the feeling that I'm learning in the process, instead of just copying and pasting codes from stackoverflow and chatgpt.
I want to dissect the codes, concepts and ideas of the projects to explain in an article, like this. I believe that this way I would be able to absorb the knowledge behind the production of project codes.
Of the three projects, none prove to be very simple. So I thought about building a fourth project, simpler, shorter and where I can learn something.
Something is better than nothing. And nothing is better than anything unfinished.
But anyway, let's do it!
Ah, the name is really funny, but I thought about the concept of f-string, where you introduce a string into some code.
As for the cat... well, there you got me. People like cats. Added to this, I thought Nietzsche would be a cat, instead of a dog, a butterfly, an elephant, a dinosaur or a sloth. So that's it. It's a cat, because YES.
We start with the fact that we already have a txt file with Nitzsche's quotes. The program needs to select one of these at random and make it available to the user. Additionally, you need to print the cat in ASCII and form a speech bubble around the displayed quote.
In short:
File with quotes: .txt file with quotes from Nietzsche, where each quote is on a separate line.
Cat drawing in ASCII: Let's define the cat drawing that will be printed in the terminal.
I liked this one. He has mesmerizing eyes.
,_ _ |\_,-~/ / _ _ | ,--. ( @ @ ) / ,-' \ _T_/-._( ( / `. \ | _ \ | \ \ , / | || |-_\__ / ((_/`(____,-'
Load and select a random quote: The program will read the quotes from a .txt file and select one at random.
Print quote with speech bubble: The quote will be displayed inside a speech bubble above the cat.
First of all:
Create a directory for the project and navigate to it:
mkdir fcat cd fcat
Create a main.go file:
touch main.go
Initialize go modules:
go mod init main.go
Your directory should look like this:
fcat . ├── go.mod ├── main.go └── quotes.txt
Now open main.go in your preferred IDE.
NVIM if it's hype XD
This function opens the citation file (nietzsche.txt), reads each line, and stores all citations in a list.
The function will not receive arguments, it will just return a list/slice of strings and error: string and error:
,_ _ |\_,-~/ / _ _ | ,--. ( @ @ ) / ,-' \ _T_/-._( ( / `. \ | _ \ | \ \ , / | || |-_\__ / ((_/`(____,-'
Within the function we will initialize a slice/list to receive all quotes:
mkdir fcat cd fcat
Now, let's open the txt file:
touch main.go
Now, we will need to create a "scanner" to read our quotes file quotes.txt.
It will also need to read each line of the file.
go mod init main.go
Now, we will check the error when reading the txt file of citations and return our list with the citations that were added to it.
fcat . ├── go.mod ├── main.go └── quotes.txt
Now we need to create the main function to return the citations and check if the loadCitations function is correct:
package main import ( "fmt" "os" "bufio" ) func carregarCitations()([]string, error) { }
The code should look like this:
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string }
Now let's run the code in the terminal
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string // Abrir o arquivo txt com as citações arquivo, err := os.Open('quotes.txt') if err != nil { return nil, err // Retorna erro se falhar em abrir arquivo } defer arquivo.Close() }
You should see all the quotes in your quotes.txt file in your terminal.
This function uses the math/rand library to select a random quote from the list.
Inside the function's parentheses (), you define the parameters that the function receives as input. In the example:
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string // Abrir o arquivo txt com as citações arquivo, err := os.Open('quotes.txt') if err != nil { return nil, err // Retorna erro se falhar em abrir arquivo } defer arquivo.Close() // Criar scanner para leitura do arquivo txt scanner := bufio.NewScanner(arquivo) // Ler cada linha de cada arquivo for scanner.Scan() { linha := scanner.Text() // Obter o texto da linha citas = append(citas, linha) // Realiza a adição das linhas à lista/slice citas } }
When you call the function, you must pass a list of quotes (e.g. loaded from the quotes.txt file), and this list will be used within the function.
After the input parentheses, just before the function body {}, you specify the type of value that the function will return.
package main import ( "fmt" "os" "bufio" ) func carregarCitations([]string, error) { // Abrir uma lista para receber as citações var citas []string // Abrir o arquivo txt com as citações arquivo, err := os.Open('quotes.txt') if err != nil { return nil, err // Retorna erro se falhar em abrir arquivo } defer arquivo.Close() // Criar scanner para leitura do arquivo txt scanner := bufio.NewScanner(arquivo) // Ler cada linha de cada arquivo for scanner.Scan() { linha := scanner.Text() // Obter o texto da linha citas = append(citas, linha) // Realiza a adição das linhas à lista citas } // Verifica se houve erro na leitura do arq txt if err := scanner.Err(); err != nil { return nil, err } // Retornar nossa lista com citações return citas, nil // Retorna lista de citações }
In this case, the function will return a random quote, which is a single string.
However, we need to generate a random value, but REALLY random. If we only use rand.Seed(), the default seed will always be the same. That's why we need to pass two other functions as parameters:
time.Now(), which returns the current time
UnixNano(), which will convert this time into an integer, representing the number of nanoseconds since January 1, 1970. The high granularity that is the cat's leap XD
And then we need the function to return a random index of citations according to the size of the citation list (length)
func main() { citations, err := carregarCitations() if err != nil { fmt.Println("Erro ao carregar citações", err) return } for _, citation := range citations { fmt.Println(citation) } }
len(citations) returns the number of citations in the slice.
rand.Intn(n) generates a random number between 0 and n-1.
rand.Intn(len(citations)) selects a valid random index to access a citation from the list.
And now let's change the main function to print the random quote:
,_ _ |\_,-~/ / _ _ | ,--. ( @ @ ) / ,-' \ _T_/-._( ( / `. \ | _ \ | \ \ , / | || |-_\__ / ((_/`(____,-'
Our code should look like this:
mkdir fcat cd fcat
Now run main.go in your terminal to check if we can get a random quote:
touch main.go
This function displays a drawing of a cat in ASCII and prints the quote inside a speech bubble.
go mod init main.go
In the main() function, the program loads the quotes, selects a random one and prints the cat with the quote in a balloon.
fcat . ├── go.mod ├── main.go └── quotes.txt
Our final code should look like this:
package main import ( "fmt" "os" "bufio" ) func carregarCitations()([]string, error) { }
Now we just have to compile our program and run it.
Compile your main.go file as fcat:
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string }
And finally, execute:
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string // Abrir o arquivo txt com as citações arquivo, err := os.Open('quotes.txt') if err != nil { return nil, err // Retorna erro se falhar em abrir arquivo } defer arquivo.Close() }
This was the result:
package main import ( "fmt" "os" "bufio" ) func carregarCitations() ([]string, error) { // Abrir uma lista para receber as citações var citas []string // Abrir o arquivo txt com as citações arquivo, err := os.Open('quotes.txt') if err != nil { return nil, err // Retorna erro se falhar em abrir arquivo } defer arquivo.Close() // Criar scanner para leitura do arquivo txt scanner := bufio.NewScanner(arquivo) // Ler cada linha de cada arquivo for scanner.Scan() { linha := scanner.Text() // Obter o texto da linha citas = append(citas, linha) // Realiza a adição das linhas à lista/slice citas } }
I found it interesting how something so simple can become so complicated to execute.
But what impressed me was the program's opening line: "He who has a why to live for can bear almost any how"
May the sentence above inspire you to continue learning.
ions,
Another day on earth
The above is the detailed content of Nietzsche reincarnated in a cat, a 'tool' CLI made with GO. For more information, please follow other related articles on the PHP Chinese website!