GithubHelp home page GithubHelp logo

dotmoji's Introduction

dotmoji

A Go CLI to generate emoji sequences.

References

Notes

  • Circles.
  • Go is an object-oriented language (in its own way).
  • Uninstall Go.
  • VS Code Go extension.
  • Commands:
    • go version (Go 1.16).
    • go run main.go.
    • go run main.go utils.go.
  • Numeric types and types.
  • fmt:
    • %f: For floats.
    • %0.1f: One decimal place.
  • Standard library (built-in packages).
  • Go is a pass-by-value language (it creates "copies" of values when passed into functions).
  • Non-pointer values:
    • Strings.
    • Ints.
    • Floats.
    • Booleans.
    • Arrays.
    • Structs.
  • Pointer wrapper values:
    • Slices.
    • Maps.
    • Functions.
  • Pointers:
    • A pointer holds the memory address of a value.
    • &: pointer.
    • *: pointer's underlying value.
    • Use an asterisk (*) before the type of an argument in a function for pointers.
  • Switch documentation.
  • panic(err) (source): to abort if a function returns an error that we don't want or know how to handle.
  • An interface groups types based on their methods (example).
  • Toggle Use Regular Expression in the search bar in VS Code to search for \t (source).

Course file (main.go)

package main

import (
    "bufio"
    "fmt"
    "os"
    "sort"
    "strconv"
    "strings"
)

// Can be used as a type for function arguments, for example.
type shape interface {
    area() float64
    perimeter() float64
}

// Custom type/blueprint.
type person struct {
    name string
    age  int
}

func newPerson(name string, age int) person {
    p := person{
        name: name,
        age:  age,
    }

    return p
}

// Receiver function.
// `(p person)` or `(p *person)`.
func (p person) format() string {
    return fmt.Sprintf("Person: %v (%v years old)", p.name, p.age)
}

// Receiver function with pointer.
// For structs, pointers are automatically dereferenced.
func (p *person) updateAge(age int) {
    // (*p).age = age
    // or
    p.age = age
}

func sayHello(n string) {
    fmt.Printf("Hello, %v!\n", n)
}

// `string` -> `(string, string)` if multiple return values.
func prepareHello(n string) string {
    return fmt.Sprintf("Hello, %v!", n)
}

func cycleNames(n []string, f func(string)) {
    for _, v := range n {
        f(v)
    }
}

// Helper function.
// `reader := bufio.NewReader(os.Stdin)`.
func getInput(prompt string, r *bufio.Reader) (string, error) {
    fmt.Print(prompt)

    input, err := r.ReadString('\n')

    return strings.TrimSpace(input), err
}

// Application entry point.
func main() {
    // Type (`string`) can be omitted.
    var message string = "Hello, World!"

    // var message string

    // Shorthand.
    // Cannot be used outside of a function.
    // message := "Hello, World!"

    // fmt.Print(message)
    fmt.Println(message)

    // Printf (formatted strings).
    // Add `\n` so that `%` does not appear
    // at the end of the string on the command
    // line (https://stackoverflow.com/a/22816721)

    // `%v` (format specifier): Default format.
    fmt.Printf("Message: %v\n", message)

    // `%q`: Put quotes around the variable (for strings).
    fmt.Printf("Message: %q\n", message)

    // `%T`: Get the variable type.
    fmt.Printf("Message: %T\n", message)

    // Sprintf (save formatted strings).
    var longMessage string = fmt.Sprintf("Message: %v", message)
    fmt.Println(longMessage)

    // Array (fixed length).
    // var numbers [3]int = [3]int{1, 2, 3}
    // var numbers = [3]int{1, 2, 3}
    numbers := [3]int{1, 2, 3}
    numbers[1] = 4

    fmt.Println(numbers, len(numbers))

    // Slices (closer to JavaScript arrays, for example).
    var scores = []int{100, 200, 300}
    scores[1] = 50

    // It is not possible to do this with arrays.
    scores = append(scores, 500)

    fmt.Println(scores, len(scores))

    // Slice ranges.
    rangeNumbers := numbers[1:3]
    fmt.Println(rangeNumbers)

    // strings package.
    fmt.Println(strings.Contains(message, "Hello"))
    fmt.Println(strings.ReplaceAll(message, "Hello", "Hi"))
    fmt.Println(strings.ToUpper(message))
    fmt.Println(strings.Index(message, "ll")) // Position.
    fmt.Println(strings.Split(message, " "))

    // sort package.
    // `sort.Strings()` for strings.
    sort.Ints(scores) // In-place.
    fmt.Println(scores)

    // `sort.SearchStrings()` for strings.
    fmt.Println(sort.SearchInts(scores, 50)) // Position.

    // `for` is also used for while loops.
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }

    // If one of the two is not needed, use `_`.
    for index, value := range numbers {
        fmt.Println(index, value)
    }

    // `if`, `else if`, and `else`.
    // `continue` and `break`.

    sayHello("World")
    fmt.Println(prepareHello("World"))

    cycleNames([]string{"John", "Mary"}, sayHello)

    // Maps: Similar to Python dictionaries.
    // `map[<keys>]<values>`.
    itemPrices := map[string]float64{
        "item1": 4.99,
        "item2": 7.99,
    }

    fmt.Println(itemPrices)
    fmt.Println(itemPrices["item1"])

    for key, value := range itemPrices {
        fmt.Println(key, value)
    }

    myPerson := newPerson("João", 25)

    fmt.Println(myPerson)
    fmt.Println(myPerson.format())

    myPerson.updateAge(26)
    fmt.Println(myPerson.format())

    num, err := strconv.ParseFloat("25.5", 64)

    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("Number (%T): %0.1f\n", num, num)
    }

    // Save file.
    os.WriteFile("message.txt", []byte(message), 0644)
}
  • Blog post and repo.
  • Cobra generator (to bootstrap the CLI application):
    • cobra init --pkg-name github.com/joaopalmeiro/dotmoji (templates).
    • cobra --viper=false init --pkg-name github.com/joaopalmeiro/dotmoji (no Viper for configuration to keep things simpler the first time).
    • cobra --help.
  • Go modules (to handle the dependencies): go mod init github.com/joaopalmeiro/dotmoji + go mod tidy.
  • Run the CLI application:
    • go run main.go.
    • go install github.com/joaopalmeiro/dotmoji + dotmoji --help.
  • When running go run main.go for the first time, all dependencies will be installed and a go.sum file (lockfile) will be created.
  • To add a new command (camelCase): cobra add <name>.

~/.cobra.yaml file

author: João Palmeiro <[email protected]>
license: MIT

~/.zshrc file

Source.

# Run `go env GOPATH`.
export GOPATH="/Users/joao.palmeiro/go"

export PATH="$GOPATH/bin:$PATH"
  • Create subcommand-based CLIs.
  • Intelligent suggestions (Did you mean this?).
  • Basic pattern: APPNAME VERB NOUN --ADJECTIVE or APPNAME COMMAND ARG --FLAG. In other words, Commands represent actions, Args are "things", and Flags are modifiers for those actions.
  • User guide.

Go for JavaScript Developers (by Brenna Martenson/Frontend Masters)

dotmoji's People

Contributors

joaopalmeiro avatar

Watchers

 avatar

dotmoji's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.