GitHub - SimonWaldherr/golang-examples: Go(lang) examples - (explain the basics of #golang) (original) (raw)
Go Examples
Use the online live editor with Golang support. Edit and run the examples directly in your browser:
If you liked this project, you may also like
my golang-benchmarks repository:
my gotools repository:
my sql-examples repository:
my rp2040-examples repository:
or my rpi-examples repository:
About
These examples explain the basics of Golang. There will be more examples from time to time.
if you like, feel free to add more Golang examples. Many thanks to all contributors.
Install go(lang)
with homebrew:
with apt-get:
sudo apt-get install golang
install Golang manuallyorcompile it yourself
Examples
The examples are divided into three levels of difficulty. The Beginner section contains very easy examples, starting with Hello World but also containing a few easy algorithms. The Advanced section uses more complicated features of Golang. Finally, the Expert section contains applications like telnet-clients or http-server (even with SSL). If you want even more Golang examples, you can take a look at my other go repositories at GitHub:
- golang-benchmarks shows how to benchmark the execution time of Golang functions
- GolangSortingVisualization visualizes various sorting algorithms on the terminal or as gif
- golang-minigames currently only contains a snake clone
- bbmandelbrot.go calculates a Mandelbrot Fractal and saves it as PNG
- golibs contains various Go packages (e.g. math, converter, stack, cli, ...)
- fsagent watch a folder for new or modified files and do something
- cgol.go is Conway's Game of Life in Golang
- micromarkdownGo converts markdown to html (via regular expression)
- wikiGo is a wiki software in Go
- WorkingTimeMeasurementSystem demonstrates how to create a simple time tracking system using Golang and SQLite
- zplgfa is an image converter to print pictures on zpl compatible labels
- ...
All of them are published as free and open source software.
If all of this is even not enough for you, you can take a look at the following websites:
Beginner
To execute a Golang program, write go run at the cli followed by the name of the file.
You also can convert the file to a binary executable program by the command go build.
If you know #!, also known as Shebang, there is an equivalent for go: //usr/bin/env go run <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>0</mn></mrow><annotation encoding="application/x-tex">0 </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">0</span></span></span></span>@ ; exit
Print Hello World with comments (Golang Playground)
Print Hello World with comments (shebang version)
Declare variables and print them (Golang Playground)
Various ways (and styles) to print variables (Golang Playground)
If statement in Golang (Golang Playground)
Declare array and print its items (Golang Playground)
Declare your own functions (Golang Playground)
Do something multiple times (Golang Playground)
Read via cli provided input data (Golang Playground)
go run args.go string string2
Read via cli provided input data (Golang Playground)
Or scan for it (Golang Playground)
Read named argument input data (Golang Playground)
Return the working directory (Golang Playground)
Return the current time/date in various formats (Golang Playground)
Return pseudo random integer values (Golang Playground)
Concat strings in two different ways (Golang Playground)
Modulo operation finds the remainder of division (Golang Playground)
Split a string by another string and make an array from the result (Golang Playground)
An example implementation of the Ackermann function (Golang Playground)
An example implementation of the Euclidean algorithm (Golang Playground)
Submit a function as argument (Golang Playground)
go run functioncallback.go
A function returned by a function (Golang Playground)
go run functionclosure.go
A function with an unknown amount of inputs (variadic function) (Golang Playground)
go run functionvariadic.go
Empty interface as argument (You Don't Know Type) (Golang Playground)
Execute Shell/Bash commands and print its output values (Golang Playground)
Make structs (objects) which have functions (Golang Playground)
Dependency injection for easier testing
Hashing (md5, sha) in go (Golang Playground)
Advanced
Benchmarking example (using JSON marshal and unmarshal for the sample) (Golang Playground) From the root directory ($GOPATH/github.com/SimonWaldherr/golang-examples), run this command:
go test -bench=. -benchmem advanced/json_bench/main_test.go
Make pipe-able unix applications with os.Stdin (Golang Playground)
AES-GCM encryption example (Golang Playground)
Bcrypt hashing example (Golang Playground) Please install package golang.org/x/crypto/bcrypt before run this file by running go get golang.org/x/crypto/bcrypt
Search element is exist in arrays or not (Golang Playground)
Calculate triangles (Golang Playground)
go run pythagoras.go (float|?) (float|?) (float|?)
Read from stdin (but don't wait for the enter key)
Wait and sleep (Golang Playground)
Last in - first out - example (Pop and push in Golang) (Golang Playground)
Split a string via regular expression and make an array from the result (Golang Playground)
More advanced regex (with time and dates) (Golang Playground)
Use my golibs regex package and have fun (Golang Playground)
Calculate and print the fibonacci numbers (Golang Playground)
Calculate and print the requested (32th) prime number (Golang Playground)
Do things with numbers, strings and switch-cases (Golang Playground)
Use a template to create and fill documents (this example uses LaTeX) (Golang Playground)
go run template.go pdflatex -interaction=nonstopmode template_latex.tex
Start a ticker (do things periodically)
Do something in case of a timeout (Golang Playground)
Convert go object to json string (Golang Playground)
Run unix/shell commands in go apps
Compress by pipe
Compress by file
Parse CSV (Golang Playground)
Convert CSV to a Markdown table (Golang Playground)
Parse a XML string into a Struct with undefined Fields (Golang Playground)
Run a self killing app
GoCV : hello video
GoCV : face detection
go run face_detect.go 0 model/haarcascade_frontalface_default.xml
Run the example for generic (Golang Playground)
Expert
Calculate π with go (leibniz, euler and prime are running until you stop it via CTRL+C)
go run pi2go.go leibniz go run pi2go.go euler go run pi2go.go prime
Calculate π with go - same as above - but with live output (based on gcurses)
go run pi2go-live.go leibniz go run pi2go-live.go euler go run pi2go-live.go prime
List files in working directory
run assembly code from golang
run C code from golang
generate Go code with golang templates
Convert from rgb to hsl (Golang Playground)
Telnet with Golang
The smallest Golang http server
Secure Golang http server
The smallest Golang http proxy
Read and write cookies
Demonstrate the power of multithreading / parallel computing you have to set GOMAXPROCS to something greater than 1 to see any effect
export GOMAXPROCS=8 time go run parallel.go true time go run parallel.go false
A dynamic amount of channels
time go run dynparallel.go 8
Run the compiler and comment each line which contains an error
go build gocomment.go ./gocomment go-app.go
Convert a image to a grayscale and to a color inverted image
Generate an image with three colored circles (with intersection)
Generate an image representing the Mandelbrot fractal
Sql (sqlite) Golang example
maybe you also wanna take a look at my sql-examples-project
go run sqlite.go insert test go run sqlite.go select
Public-key/asymmetric cryptography signing and validating
Command Line Arguments Golang Example We can get argument values though command line by specifying the operator '-' with the name of the argument and the value to be set. E.g. -env=qa
go run command_line_arguments.go go run command_line_arguments.go -env=qa -consumer=true
Cron Golang Example We can trigger a function at a particular time through cron
Map Golang Example Hash Map standard functions in golang
TinyGo
You can even use Go on microcontrollers, the keyword here is TinyGo, a go compiler specially developed for SBCs and MCUs.
If you want to blink the LED of your Raspberry Pi Pico, try this:
tinygo build -o firmware.uf2 -target=pico ./tinygo/blink.go
and then upload it to the pico.
Compile
One great aspect of Golang is, that you can start go applications via go run name.go, but also compile it to an executable with go build name.go. After that you can start the compiled version which starts much faster. If you start fibonacci.go and the compiled version you will notice, that the last line which contains the execution time doesn't differ much, but if you start it with time ./fibonacci 32 and time go run ./fibonacci.go 32 you will see the difference.
License
Copyright © 2024 Simon Waldherr Dual-licensed. See the LICENSE file for details.