search
HomeBackend DevelopmentGolangNietzsche reincarnated in a cat, a \'tool\' CLI made with GO

Nietzsche reencarnado num gato, uma

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!

FCAT?

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.

What's the problem?

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.

Letes go, baby

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

Code explanation:

loadCitations function

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.

getRandomCitation function

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:

  • citations []string means that the getRandomCitation function expects an argument called citations, which is a slice of strings (that is, a list of strings).
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
    }
}

  • []string is Go's syntax for "a slice of strings", i.e. an ordered collection of strings.

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.

  • string right after the parentheses means that the function will return a string when finished executing.
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

Print functionCat

This function displays a drawing of a cat in ASCII and prints the quote inside a speech bubble.

go mod init main.go

main function

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) {
}

Finishing

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

Go 'bytes' package quick referenceGo 'bytes' package quick referenceMay 13, 2025 am 12:03 AM

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor